我正在撰寫一些集成測驗,我需要在其中發送 api 呼叫以創建資源,然后基于該資源執行后續 api 呼叫。我想在我的@BeforeAll 方法中發送第一個呼叫。
在我的測驗課上:
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
@ActiveProfiles("test")
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
public class ExampleResourceTest {
@Autowired
private MockMvc mockMvc;
@BeforeAll
private void createExampleResource() throws Exception {
Map<String, Object> requestBody = new HashMap<>();
requestBody.put("email", "[email protected]");
requestBody.put("username", "example");
requestBody.put("firstName", "Example");
requestBody.put("lastName", "Name");
requestBody.put("password", "@password123");
Gson gson = new Gson();
String json = gson.toJson(requestBody);
mockMvc.perform(
post("/api/v1/resourcename")
.contentType(MediaType.APPLICATION_JSON)
.content(json));
}
// More stuff...
}
但是,在類中運行測驗之前,未呼叫帶注釋的@BeforeAll 方法。
正如我從試圖找到解決方案中了解到的那樣,@BeforeAll 方法需要是靜態的。但是,那么我將無法使用我注入的 MockMvc。我也試過用 注釋我的測驗類
@TestInstance(TestInstance.Lifecycle.PER_CLASS),但我也沒有遇到過運氣。
uj5u.com熱心網友回復:
我相信@BeforeAll不應該是私人的,但你已經添加了。這就是它不呼叫您的方法的原因。
參考: https ://junit.org/junit5/docs/5.0.0/api/org/junit/jupiter/api/BeforeAll.html
uj5u.com熱心網友回復:
原來我在 junit 4 上,需要使用 @BeforeClass 才能呼叫它。我最終改為使用 @Before 方法并僅使用布林值來檢查是否已經進行了呼叫。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/535631.html
