[英]Spring Boot testing, migrate from 1.3 to 1.5
我將spring-boot項目從1.3.x更新為1.5.2。 測試框架已“更改”,我正在嘗試遷移我的代碼。 來自RestTemplate的響應狀態代碼應為401,但是當我將代碼更改為新的“結構”時,我得到404,未找到。 可能遺漏的任何想法?
舊代碼:
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = ApiAuthServerApplication.class)
@WebAppConfiguration
@IntegrationTest("{server.port:0, server.address:localhost}")
public class ApiEndpointTests {
@Value("${local.server.port}")
private int port;
private RestTemplate template = new TestRestTemplate();
@Test
public void clientsEndpointProtected() {
ResponseEntity<String> response = template.getForEntity("http://localhost:"
+ port + "/uaa/api/v1/oauth/clients", String.class);
assertEquals(HttpStatus.UNAUTHORIZED, response.getStatusCode());
}
}
我試過的新代碼:
@RunWith(SpringRunner.class)
@SpringBootTest(classes = ApiAuthServerApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class ApiEndpointTests {
@LocalServerPort
private int port;
private TestRestTemplate template = new TestRestTemplate();
@Test
public void clientsEndpointProtected() {
ResponseEntity<String> response = template.getForEntity("http://localhost:"
+ port + "/uaa/api/v1/oauth/clients", String.class);
assertEquals(HttpStatus.UNAUTHORIZED, response.getStatusCode());
}
}
還嘗試@Autowire
TestRestTemplate並省略請求中的主機名和端口。
當您使用WebEnvironment.RANDOM_PORT時,sprint測試框架將處理主機和端口的配置和設置。 因此,您可以刪除主機和端口的詳細信息。 您還應該在TestRestTemplate上使用@Autowired注釋。
@Autowired for the TestRestTemplate.
@RunWith(SpringRunner.class)
@SpringBootTest(classes = ApiAuthServerApplication.class, webEnvironment =
SpringBootTest.WebEnvironment.RANDOM_PORT)
public class ApiEndpointTests {
@Autowired
private TestRestTemplate template = new TestRestTemplate();
@Test
public void clientsEndpointProtected() {
ResponseEntity<String> response =
template.getForEntity("/uaa/api/v1/oauth/clients", String.class);
assertEquals(HttpStatus.UNAUTHORIZED, response.getStatusCode());
}
}
弄清楚了。
使用此代碼時:
@RunWith(SpringRunner.class)
@SpringBootTest(classes = ApiAuthServerApplication.class, webEnvironment =
SpringBootTest.WebEnvironment.RANDOM_PORT)
public class ApiEndpointTests {
@Autowired
private TestRestTemplate template;
@Test
public void clientsEndpointProtected() {
ResponseEntity<String> response =
template.getForEntity("/uaa/api/v1/oauth/clients", String.class);
assertEquals(HttpStatus.UNAUTHORIZED, response.getStatusCode());
}
}
我還需要刪除/uaa
因為這是上下文路徑。 我想TestRestTemplate
也會自動包含它。 所以最終的代碼有效:
@RunWith(SpringRunner.class)
@SpringBootTest(classes = ApiAuthServerApplication.class, webEnvironment =
SpringBootTest.WebEnvironment.RANDOM_PORT)
public class ApiEndpointTests {
@Autowired
private TestRestTemplate template;
@Test
public void clientsEndpointProtected() {
ResponseEntity<String> response =
template.getForEntity("/api/v1/oauth/clients", String.class);
assertEquals(HttpStatus.UNAUTHORIZED, response.getStatusCode());
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.