因为近期在开发没有界面,只有接口的。项目架构如下

SpringMVC + Mybatis

一般来说只要测试Service层即可。

一、所需Jar

JUnit 4

Spring Test

Spring 相关其他依赖包

二、写测试案例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
package com.xidian.wq.imaopay.controller.webservice;
 
import javax.annotation.Resource;
 
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
 
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations =
{
        "classpath:spring.xml",
        "classpath:spring-mvc.xml",
        "classpath:spring-mybatis.xml"
})
public class QueryControllerTest extends AbstractJUnit4SpringContextTests{
     
    @Resource
    private QueryController queryController;
     
    @Test
    public void testGetRepayCashFlow()
    {
        String openCode = "d370f9630b0cc559a139be8db774e1e9ed15118f49d2c9f82acf62a3e2809d47";
        String repayId = "1350";
        String xmlStr = queryController.getRepayCashFlow(openCode, repayId);
        System.out.println(xmlStr);
    }
}

代码详解如下:

1、测试类的包名注意方便自己管理

2、SpringJUnit4ClassRunner.class 表示运用JUnit4进行测试

3、ContextConfiguration 表示指定配置文件所在的位置

另外,类头部还可以加上。可以设置事务如下:

@TransactionConfiguration(transactionManagert=”txMgr”,defaultRollback=false) 
@Transactional

4、@Resource
注解被用来**一个命名资源(named resource)的依赖注入。其中指有个name为“queryController”已经注入为bean。这里插一句核心的话:

“测试Controller时,并没有这个bean,怎么办呢? 可以直接在将Controller作为一个service层。即加入注解 @Service即可”

5、@Test标注在方法前,表示一个测试的方法

三、运行测试

笔者用fastJson,直接栈溢出了。后来debug得知是,fastjson问题。

如图,Junit Test即可

Spring Test:Spring Test 4 整合 JUnit 4 使用


相关文章: