我在Spring Boot上有一个IT
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = Application.class)
public class CustomerControllerIT {
private RestTemplate restTemplate = new RestTemplate();
@Test
public void findAllCustomers() throws Exception {
ResponseEntity<List<Customer>> responseEntity = restTemplate.exchange(
"http://localhost:8080/Customer", HttpMethod.GET, null,
new ParameterizedTypeReference<List<Customer>>() {
});
List<Customer> list = responseEntity.getBody();
Assert.assertEquals(list.size(), 0);
}
如果我在已启动的应用程序上启动测试-测试正常 如果我仅尝试启动IT,则出现连接被拒绝错误。
我的application.properties对于一次启动和测试都是相同的,并且位于资源和testResources中。
Application.class是
package mypackage;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
@ComponentScan({"mypackage"})
@EntityScan(basePackages = {"mypackage.model"})
@EnableJpaRepositories(basePackages = {"mypackage.persistence"})
@SpringBootApplication
public class Application extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
答案 0 :(得分:1)
您必须在正在运行的服务器上运行测试,
如果需要启动正在运行的服务器,则必须使用随机端口,并且如果使用 @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) ,则可用端口每次运行测试时都会随机选择。
您需要此Maven依赖项
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-test</artifactId>
</dependency>
请阅读文档,以了解更多reference
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment=WebEnvironment.RANDOM_PORT)
public class TestRest {
@Autowired
private TestRestTemplate restTemplate;
@Test
public void findAllCustomers() throws Exception {
ResponseEntity<List<Customer>> responseEntity = restTemplate.exchange(
"/Customer", HttpMethod.GET, null,
new ParameterizedTypeReference<List<Customer>>() {
});
List<Customer> list = responseEntity.getBody();
Assert.assertEquals(list.size(), 0);
}
}
答案 1 :(得分:1)
@SpringBootTest
,您可以使用:@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
class MyUnitTests {
@Test
void checkActuator() throws Exception {
final String url = "http://localhost:8080/actuator/health";
@SuppressWarnings("rawtypes")
ResponseEntity<Map> re = new RestTemplate().getForEntity(url, Map.class);
System.out.println(re);
assertEquals(HttpStatus.OK, re.getStatusCode());
re.getStatusCode();
}
}
并将端口属性添加到您的 application.yml
(在文件夹 src/main/resources
内):
server:
port: 8080
或者如果有 application.properties
:
server.port=8080