十年匠心定制 · 商业建站与技术教学双线并行 咨询热线:400-886-1026 service@lmnt.cn
ARTICLE DETAIL

资讯详情

深耕网站建设与运营推广的一线实战洞察。

springboot集成test测试、junit4、junit5

springboot集成test测试、junit4、junit5 文章目录junit5引入maven依赖(推荐用spring的方式)引入maven依赖(非spring项目)junit4Test注解报红最新的是junit5也推荐用这个。junit和mockito通常配套使用所以文档中也可能出现mockito。junit5引入maven依赖(推荐用spring的方式)spring-boot-starter-test已经自带JUnit5 Mockito不需要单独引入mockito。dependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-test/artifactIdscopetest/scope/dependency引入maven依赖(非spring项目)!-- JUnit5 --dependencygroupIdorg.junit.jupiter/groupIdartifactIdjunit-jupiter-api/artifactIdversion5.9.2/versionscopetest/scope/dependencydependencygroupIdorg.junit.jupiter/groupIdartifactIdjunit-jupiter-engine/artifactIdversion5.9.2/versionscopetest/scope/dependency!-- Mockito --dependencygroupIdorg.mockito/groupIdartifactIdmockito-core/artifactIdversion4.11.0/versionscopetest/scope/dependencydependencygroupIdorg.mockito/groupIdartifactIdmockito-junit-jupiter/artifactIdversion4.11.0/versionscopetest/scope/dependencyjunit4scope为test有可能编译不通过去掉那行即可。pom.xml添加dependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-test/artifactIdscopetest/scopeexclusionsexclusiongroupIdorg.junit.vintage/groupIdartifactIdjunit-vintage-engine/artifactId/exclusion/exclusions/dependencydependencygroupIdjunit/groupIdartifactIdjunit/artifactIdversion4.12/versionscopetest/scope!-- 如果编译不通过去掉这行即可 --/dependency使用MockMvc代码RunWith(SpringRunner.class)// 用什么来运行测试例如可以用Junit4.Class SpringBootTest // 替代ContextConfiguration来指定上下文 AutoConfigureMockMvc // 模拟web环境,因为SpringBootTest并不启动server public class MockMvcExampleTests{Autowired private MockMvc mvc;Test public void exampleTest()throws Exception{this.mvc.perform(get(/)).andExpect(status().isOk()).andExpect(content().string(Hello World));}}如果要用WebTestClient那么需要加入spring-webflux暂不讨论。使用TestRestTemplate代码RunWith(SpringRunner.class)SpringBootTest(webEnvironmentWebEnvironment.RANDOM_PORT)public class RandomPortTestRestTemplateExampleTests{Autowired private TestRestTemplate restTemplate;Test public voidexampleTest(){String bodythis.restTemplate.getForObject(/, String.class);assertThat(body).isEqualTo(Hello World);}}如果RunWith注解等无法使用要确定test文件夹已经设置为source文件夹否则无法import类的。官网文档地址:springboot官网2.1.0文档Test注解报红先给类加上RunWith(SpringJUnit4ClassRunner.class)即可。
返回列表