江西省城乡建设陪训网官方网站,企业做网站维护,滦南网站建设推广,互联网教育网站开发博文引用#xff1a;springboot(十二)#xff1a;springboot如何测试打包部署
开发阶段 单元测试
Spring boot对单元测试的支持已经很完善了。
1 在pom包中添加Spring-boot-starter-test包引用
dependencygroupIdorg.springframework.boot/groupIdspringboot(十二)springboot如何测试打包部署
开发阶段 单元测试
Spring boot对单元测试的支持已经很完善了。
1 在pom包中添加Spring-boot-starter-test包引用
dependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-test/artifactIdscopetest/scope
/dependency2 开发测试类
头部添加RunWith(SpringRunner.class)和SpringBootTest注解在测试方法上添加 测试方法Test即可。
RunWith(SpringRunner.class)
SpringBootTest
public class ApplicationTests {Testpublic void hello() {System.out.println(hello world);}
}实际使用中可以按照项目的正常使用注入dao层或是service层代码进行测试验证spring-boot-starter-test提供很多基础用法更难得的是增加了对Controller层测试的支持。
//简单验证结果集是否正确
Assert.assertEquals(3, userMapper.getAll().size());//验证结果集提示
Assert.assertTrue(错误正确的返回值为200, status 200);
Assert.assertFalse(错误正确的返回值为200, status ! 200);引入MockMvc支持对Controller层的测试简单实例
public class HelloControlerTests {private MockMvc mvc;//初始化执行Beforepublic void setUp() throws Exception {mvc MockMvcBuilders.standaloneSetup(new HelloController()).build();}//验证controller是否正常响应并打印返回结果Testpublic void getHello() throws Exception {mvc.perform(MockMvcRequestBuilders.get(/hello).accept(MediaType.APPLICATION_JSON)).andExpect(MockMvcResultMatchers.status().isOk()).andDo(MockMvcResultHandlers.print()).andReturn();}//验证controller是否正常响应并判断返回结果是否正确Testpublic void testHello() throws Exception {mvc.perform(MockMvcRequestBuilders.get(/hello).accept(MediaType.APPLICATION_JSON)).andExpect(status().isOk()).andExpect(content().string(equalTo(Hello World)));}
}单元测试时验证你代码的第一道屏障要养成每写一部分代码就进行单元测试的习惯不要等到全部集成后进行测试集成后因为更关注整体运行效果很容易遗漏掉底层的bug。
集成测试
整体开发完成之后进入集成测试spring boot 项目的启动入口在Application类中直接运行run方法就可以启动项目但是在调试的过程中我们肯定需要不断的去调试代码spring boot 给出了对热部署的支持很方便的在web项目中调试。
pom需要添加以下配置 dependenciesdependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-devtools/artifactIdoptionaltrue/optional/dependency
/dependenciesbuildpluginsplugingroupIdorg.springframework.boot/groupIdartifactIdspring-boot-maven-plugin/artifactIdconfigurationforktrue/fork/configuration/plugin/plugins
/build添加以上配置后项目就支持了热部署非常方便集成测试。
投产上线