0
点赞
收藏
分享

微信扫一扫

springboot集成test测试(用junit4)

禾木瞎写 2023-02-28 阅读 111


scope为test有可能编译不通过,去掉那行即可。
pom.xml添加:

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</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(webEnvironment = WebEnvironment.RANDOM_PORT)
public class RandomPortTestRestTemplateExampleTests {

@Autowired
private TestRestTemplate restTemplate;

@Test
public void exampleTest() {
String body = this.restTemplate.getForObject("/", String.class);
assertThat(body).isEqualTo("Hello World");
}
}

如果​​@RunWith​​注解等无法使用,要确定test文件夹已经设置为source文件夹,否则无法import类的。

官网文档地址:
​​​springboot官网2.1.0文档​​

@Test注解报红

先给类加上 ​​@RunWith(SpringJUnit4ClassRunner.class)​​ 即可。


举报

相关推荐

0 条评论