用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