用spring boot 2.2和junit5时,我需要完成一些integration test.在写integration test时我有如下的代码用于启动一个测试环境:
import org.junit.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
@ExtendWith(SpringExtension.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
public class DemoApplicationTests {
@LocalServerPort
private int port;
@Test
public void printPort() throws Exception {
assertNotEquals(port, 0);
}
}
但是在测试的时候发现port一直为0.
原因是test case的@Test注解导入的是junit4的
import org.junit.Test;
删除重新导入junit5的注解即可:
import org.junit.jupiter.api.Test

在使用Spring Boot 2.2进行Integration Test时,作者遇到一个问题:测试环境中@LocalServerPort注解的port始终为0。问题的根源在于错误地导入了JUnit4的@Test注解,而非JUnit5的。解决方案是将@Test注解替换为JUnit5的@Test。修正后,测试能够正确运行,port不再为0。
3万+

被折叠的 条评论
为什么被折叠?



