springboot单元测试
程序员文章站
2022-04-26 09:40:51
...
controller层测试:
@RunWith(SpringJUnit4ClassRunner.class)
//开启web上下文测试
@WebAppConfiguration
@SpringBootTest
public class ControllerTest {
//注入webApplicationContext
@Autowired
private WebApplicationContext webApplicationContext;
private MockMvc mockMvc;
//设置mockMvc
@Before
public void setMockMvc() {
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
}
@Test
public void login(){
try {
JSONObject jsonObject = new JSONObject();
jsonObject.put("userName", "liuys26");
jsonObject.put("userPw", "123");
jsonObject.put("cityCode", "801000");
jsonObject.put("userType", "0");
mockMvc.perform(MockMvcRequestBuilders.post("/directive/subjectRule/getCheckDlList")
.contentType(MediaType.APPLICATION_JSON)
.content(jsonObject.toJSONString())
).andExpect(MockMvcResultMatchers.status().isOk())
.andDo(MockMvcResultHandlers.print());
} catch (Exception e) {
e.printStackTrace();
}
}
}
service层测试:
构建父类:
@RunWith(SpringRunner.class)
@SpringBootTest(classes =CenterDirectiveApplication.class )
//由于是Web项目,Junit需要模拟ServletContext,因此我们需要给我们的测试类加上@WebAppConfiguration。
//@WebAppConfiguration
public class UnitTestSerivce {
@Before
public void init() {
System.out.println("开始测试-----------------");
}
@After
public void after() {
System.out.println("测试结束-----------------");
}
}
创建子类:
public class UnitTestServiceImpl extends UnitTestSerivce {
@Autowired
private SubjectRuleService subjectRuleService;
@Autowired
private SubjectRuleDao subjectRuleDao;
@Test
public void test() {
ProfessionBigTypeVO item=new ProfessionBigTypeVO();
item.setCurrentPage(1);
item.setPageSize(10);
ResultInfo resultInfo = subjectRuleService.getCheckDlList(item);
String code=subjectRuleDao.getSubjectRuleCode();
System.out.println(JSONObject.toJSONString(code));
}
}
遇到的问题:
org.apache.ibatis.binding.BindingException: Invalid bound statement (not found): com.paic.center.directive.dao.SubjectRuleDao.getCheckDlList
上面问题出现的原因是,对应的mapper文件没有打包到编译的结果中去,开始以为配置了 就可以了,实际上在使用单元测试时读取的是test-classes下的文件内容,按照下面的方案就可以解决
解决方案:
maven的pom文件中添加如下打包命令
<build>
<testResources>
<testResource>
<directory>src/main/resources</directory>
</testResource>
</testResources>
</build>
推荐阅读