![](/img/trans.png)
[英]How do I Set-up and Tear-down variables (and driver) around my JUnit tests?
[英]How to call a set-up method before certain JUnit tests
我正在使用JUnit為操作JSON對象的方法創建單元測試。 我想在我的測試文件中創建一個方法來設置將在我的測試方法的一些但不是全部中使用的對象。 如何有選擇地運行設置方法並將其生成的JSONObject傳遞給測試方法? 有一個更好的方法嗎? 這是我在設置方法(使用gson)時的想法:
public static JsonObject prepareTestJson(){
JsonObject testJson_container = new JsonObject();
JsonObject testJson_inner = new JsonObject();
String ContactInfo = "+1 111 111 1111";
testJson_inner.addProperty("Contact", ContactInfo);
testJson_container.add("ID", testJson_inner);
return testJson_container;
}
如何有選擇地運行設置方法並將其生成的JSONObject傳遞給測試方法?
否則,您無法選擇應用@Before
注釋的方法的測試方法。
有一個更好的方法嗎?
您可以在每次測試之前調用此方法(您也可以將其設置為private
並使用實例方法來減少其訪問:
private JsonObject prepareTestJson(){
JsonObject testJson_container = new JsonObject();
JsonObject testJson_inner = new JsonObject();
String ContactInfo = "+1 111 111 1111";
testJson_inner.addProperty("Contact", ContactInfo);
testJson_container.add("ID", testJson_inner);
return testJson_container;
}
如 :
@Test
public void foo(){
JsonObject json = prepareTestJson();
...
}
另一種方法是將測試類拆分為兩個:一個測試需要setup()
,另一個測試不需要。
通過這種方式,您可以使用帶有@Before
的init方法,或者只是將這些語句放在類構造函數中。
例如 :
private JsonObject testJson_container;
@Before
public void prepareTestJson(){
testJson_container = new JsonObject();
JsonObject testJson_inner = new JsonObject();
String ContactInfo = "+1 111 111 1111";
testJson_inner.addProperty("Contact", ContactInfo);
testJson_container.add("ID", testJson_inner);
}
但這種方式是人為的/技術性的分裂,它可能使測試代碼的可讀性降低。
所以我認為在大多數情況下,我會堅持第一種方式。
此外,使用JUnit 5,您有一個有趣的解決方法:使用記錄為的@MethodSource
:
一個ArgumentsSource,它提供對聲明此批注的類的方法返回的值的訪問。
這個設計用於@ParameterizedTest
但它可能適合您的情況。
你可以寫:
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
public class FooTest {
@ParameterizedTest
@MethodSource("prepareTestJson")
void add(JsonObject testJson_container) {
// do your logic
}
private static Arguments prepareTestJson() {
JsonObject testJson_container = new JsonObject();
JsonObject testJson_inner = new JsonObject();
String ContactInfo = "+1 111 111 1111";
testJson_inner.addProperty("Contact", ContactInfo);
testJson_container.add("ID", testJson_inner);
return Arguments.of(testJson_container);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.