>>分享流行的Java框架以及开源软件,对孙卫琴的《精通Spring:Java Web开发技术详解》提供技术支持 书籍支持  卫琴直播  品书摘要  在线测试  资源下载  联系我们
发表一个新主题 开启一个新投票 回复文章 您是本文章第 17063 个阅读者 刷新本主题
 * 贴子主题:  SpringMVC下的JUnit4单元测试 回复文章 点赞(0)  收藏  
作者:Jacky    发表时间:2020-11-03 02:22:33     消息  查看  搜索  好友  邮件  复制  引用

    

简述

在spingMVC框架中,所有的类都是通过springMVC容器来加载和实例化的。

因此在junit测试的时候可以在其初始化方法中去加载spring配置文件。所有用Junit进行单元测试,都需要下面的配置。注:配置文件的加载根据自己项目的实际情况进行配置。    

@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(locations = { "classpath:config/spring-mvc.xml",
        "classpath:config/spring-resources.xml",
        "classpath:config/spring-application.xml",
        "classpath:config/spring-security.xml" })

Dao层的单元测试

通过依赖注入的方式注入测试对象;    

package com.lczyfz.zerobdt.test;

import com.lczyfz.zerobdt.modules.test.dao.TestDao;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;

import static junit.framework.TestCase.assertEquals;

/**
* Created by maple on 2018-07-01.
*/

@RunWith(SpringJUnit4ClassRunner.class)
@Transactional
@ContextConfiguration(locations = {"/spring-context.xml"})
public class TestDaoTests {
    @Autowired
    TestDao testDao;

    @Test
    public void testFindAllList(){
        System.out.println(testDao.findAllList(new com.lczyfz.zerobdt.modules.test.entity.Test()).toString());
        assertEquals(testDao.findAllList(new com.lczyfz.zerobdt.modules.test.entity.Test()).size(),13);
    }
}

  成功:

                点击在新窗口中浏览原图
CTRL+鼠标滚轮放大或缩小

              失败:

                点击在新窗口中浏览原图
CTRL+鼠标滚轮放大或缩小        

Service层的单元测试

和Dao层类似;    

package com.lczyfz.zerobdt.test;

import com.lczyfz.zerobdt.modules.test.service.TestService;
import junit.framework.TestCase;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import static junit.framework.TestCase.assertEquals;
import static org.junit.Assert.*;

/**
* Created by maple on 2018-07-01.
*/

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"/spring-context.xml"})
public class TestDaoServices {
    @Autowired
    TestService testService;

    @Test
    public void testFindAllList(){
        System.out.println(testService.get("5").toString());
        assertNotNull(testService.get("5"));
    }
}

Controller层的单元测试

package com.lczyfz.zerobdt.test;

import com.lczyfz.zerobdt.common.test.SpringTransactionalContextTests;
import com.lczyfz.zerobdt.modules.test.web.TestController;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.ResultActions;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;

import java.io.UnsupportedEncodingException;

import static org.junit.Assert.assertNotNull;

/**
* Created by maple on 2018-07-01.
*/

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"/spring-context.xml","/spring-mvc.xml"})
public class TestDaoControllers extends SpringTransactionalContextTests{
    @Autowired
    TestController testController;

    MockMvc mockMvc;

        @Before
    public void setup(){
        mockMvc = MockMvcBuilders.standaloneSetup(testController).build();
    }
    @Test
    public void testFindAllList(){
        ResultActions resultActions = null;
        try {
            resultActions = this.mockMvc.perform(MockMvcRequestBuilders.post("/show_user").param("id", "1"));
        } catch (Exception e) {
            e.printStackTrace();
        }
        MvcResult mvcResult = resultActions.andReturn();
        String result = null;
        try {
            result = mvcResult.getResponse().getContentAsString();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        System.out.println("=====客户端获得反馈数据:" + result);
        // 也可以从response里面取状态码,header,cookies...
//        System.out.println(mvcResult.getResponse().getStatus());

    }
}

  Controller层的测试建议采用Postman的方式来测试,可以记录url,同时也更符合实际情况。


----------------------------
原文链接:https://www.jianshu.com/p/8d0f7201b445

程序猿的技术大观园:www.javathinker.net



[这个贴子最后由 flybird 在 2020-11-24 20:26:14 重新编辑]
  Java面向对象编程-->输入与输出(上)
  JavaWeb开发-->JavaWeb应用入门(Ⅰ)
  JSP与Hibernate开发-->Java应用分层架构及软件模型
  Java网络编程-->基于UDP的数据报和套接字
  精通Spring-->通过Axios访问服务器
  Vue3开发-->Vue组件开发基础
  Spring事务容易掉入的坑
  Spring 5 webflux响应式编程 - 但时间也偷换概念
  WebFlux 响应式编程初体验
  新书《精通Spring:Java Web开发技术详解》出版!!!
  HandlerInterceptor与WebRequestInterceptor的异同
  Spring 自动注入的三种方式:byName、byType、constructor
  Spring MVC处理静态资源文件的方式
  Spring MVC中Controller的用法
  阿里JAVA面试题剖析:Redis 和 memcached 有什么区别?
  说说微服务的优缺点
  理解 RESTful 风格的 API
  Spring Cloud 技术栈及架构一览
  支付结算系统如何应对高并发、热点账户等问题
  Spring MVC:切面的应用
  SVN使用指南:查看历史信息的方法
  更多...
 IPIP: 已设置保密
楼主      
1页 0条记录 当前第1
发表一个新主题 开启一个新投票 回复文章


中文版权所有: JavaThinker技术网站 Copyright 2016-2026 沪ICP备16029593号-2
荟萃Java程序员智慧的结晶,分享交流Java前沿技术。  联系我们
如有技术文章涉及侵权,请与本站管理员联系。