我正在编写用于创建和更新数据的集成测试用例
@RunWith(SpringRunner.class)
@SpringBootTest(classes = MyApplication.class, webEnvironment =
SpringBootTest.WebEnvironment.DEFINED_PORT)
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class MyIntegrationTest {
private String baseUrl="http://192.168.6.177/api/v1/";
@Autowired
TestRestTemplate restTemplate;
Long createdId; // trying to set ID which is coming after test1_AddData
@Test
public void test1_AddData() throws Exception {
ABC abc = new ABC("Name");
HttpEntity<ABC> requestBodyData = new HttpEntity<>(ABC);
ParameterizedTypeReference<RestTemplateResponseEnvelope<ABC>> typeReference =
new ParameterizedTypeReference<RestTemplateResponseEnvelope<ABC>>() {
};
ResponseEntity<RestTemplateResponseEnvelope<ABC>> response = restTemplate.exchange(
baseUrl + "/presenceType",
HttpMethod.POST, requestBodyData, typeReference);
Assert.assertTrue(HttpStatus.CREATED.equals(response.getStatusCode()));
createdId = response.getBody().getData().getId();
}
@Test
public void test2_updateData() throws Exception {
ABC abc = new ABC("NEW NAME");
System.out.println("------------------------------------------" + createdId); /// it is giving null
HttpEntity<ABC> requestBodyData = new HttpEntity<>(ABC);
ResponseEntity<ABC> response = restTemplate.exchange(
baseUrl + "/presenceType/" + createdId,
HttpMethod.PUT, requestBodyData, ABC.class);
Assert.assertTrue(HttpStatus.OK.equals(response.getStatusCode()));
createdId = response.getBody().getId();
}
}
我执行的输出 ------------------------------------------空
执行此操作需要做什么,即在执行第一个函数后调用第二个函数。 注意:代码还包含需要在第三个之后调用的删除方法。
答案 0 :(得分:1)
虽然在测试中修复订单并不是一个好习惯。但是,如果您使用的是版本4.11以上的JUnit,则它具有@FixMethodOrder注释。
您可以按方法名称设置顺序。
示例:
import org.junit.runners.MethodSorters;
import org.junit.FixMethodOrder;
import org.junit.Test;
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class OrderTest {
@Test
public void test1() {
System.out.println("test1");
}
@Test
public void test2() {
System.out.println("test2");
}
}
进一步阅读@ FixMethodOder
Junit Git Page:https://github.com/junit-team/junit4/wiki/test-execution-order
自定义实施:https://memorynotfound.com/run-junit-tests-method-order/