spring单元测试

2018/08/09 SpringMVC 共 1258 字,约 4 分钟

注解配置

​ 所有用 Junit 进行单元测试,都需要下面的配置

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:applicationContext.xml"})

​ applicationContext.xml 是整个项目的 Spring 的配置文件。包括数据源配置、MVC 配置和各种 Bean 的注册扫描。如果你是多个文件,就用都好隔开写多个,像这样

{ "classpath:applicationContext.xml","classpath:servlet-context.xml"}

Dao 层的单元测试

​ 将*Mapper 接口注入进来,直接调用即可。加上@Transactional 事物管理注解以后,单元测试执行完后会撤销对数据库的修改。想看增删改的结果的话,可以把这个注解先注释。

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:spring/spring-mybatis.xml","classpath:spring/spring-mvc.xml"})
@Transactional
public class test1 {
    private static Logger logger= Logger.getLogger("test1.class");
    @Resource
    private ILogDao iLogDao=null;
    @Test
    public void t1(){
        System.out.println("\n\nTest:\n\n");
        Log log=iLogDao.selectCount();
        System.out.println(log);
        System.out.println("\n\nTest End:\n\n");

    }
}

Service 层的单元测试

Service 层的单元测试与 Dao 层基本一致,把 Service 注入进来调用就行。

Controller 层的单元测试

参考链接

没试过

一种是把 Controller 的 Bean 注入进来,调里面的方法,这很显然比较扯淡,连 Url 都没经过,只测了方法。另一种是使用 MockMvc 模拟通过 url 的接口调用。MockMvc 是 SpringMVC 提供的 Controller 测试类,每次进行单元测试时,都是预先执行@Before 中的 setup 方法,初始 healthArticleController 单元测试环境。

​ 注意:一定要把待测试的 Controller 实例进行 MockMvcBuilders.standaloneSetup(xxxxController).build(); 否则会抛出无法找到@RequestMapping 路径的异常:No mapping found for HTTP request with URI [/cms/app/getArticleList] in DispatcherServlet

Search

    Table of Contents