主要介绍如何对Springboot Service层代码做单元测试,以及单元测试中涉及外调服务时,如何通过Mock完成测试。
Springboot Service层代码单元测试:
现在项目都流行前后端代码分离,后端使用springboot框架,在service层编写接口代码实现逻辑。
假设现在前端不是你写的,你要对你自己写的后端springboot service层提供的接口方法做单元测试,以确保你写的代码是能正常工作的。
Service层代码单元测试:一个简单的service调mapper查询数据库replay_bug表数据量的接口功能
ReplayBugServiceImpl类代码:
@Service
public class ReplayBugServiceImpl implements ReplayBugService {
@Autowired
ReplayBugMapper replayBugMapper;
@Override
public int queryBugTotalCount() {
return replayBugMapper.queryBugTotalCount();
}
}
replayBugMapper.queryBugTotalCount代码:
@Select("select count(1) from replay_bug")
int queryBugTotalCount();
单元测试ReplayBugServiceImplTest类代码:
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class ReplayBugServiceImplTest{
@Autowired
ReplayBugServiceImpl replayBugService;
@Test
public void queryBugTotalCount() {
int bugCount=replayBugService.queryBugTotalCount();
System.out.println("结果是:"+bugCount);
}
}
代码很简单,调用这个接口服务,打印输出,测试是否能正确查出数据。其中关键的两个注解解释:
@RunWith(SpringRunner.class)注解:
是一个测试启动器,可以加载SpringBoot测试注解,
让测试在Spring容器环境下执行。
如测试类中无此注解,
将导致service、dao等自动注入失败。
@SpringBootTest注解:目的是加载ApplicationContext,
启动spring容器。
更进一步,测试带入参的service接口:新增接口单元测试
import com.test.service.BestTest;
import com.test.domain.UrlWhiteListVO;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
@RunWith(SpringRunner.class)
@SpringBootTest
public class ReplayUrlWhiteListServiceImplTest{
@Autowired
ReplayUrlWhiteListServiceImpl replayUrlWhiteListService;
private UrlWhiteListVO urlWhiteListVO;
@Before
public void setup(){
urlWhiteListVO=new UrlWhiteListVO();
urlWhiteListVO.setAppId(78);
urlWhiteListVO.setAppName("testAPP");
urlWhiteListVO.setUrlWhite("http://www.baidu.com");
urlWhiteListVO.setRemarks("测试一下");
}
@Test
public void save() {
System.out.println("测试结果:"+replayUrlWhiteListService.save(urlWhiteListVO));
}
}
比之前多了一个@Before注解,下面自行设置不同的参数值,测试是否在各种入参情况下接口代码都没有问题。