[英]Parameterized tests with JUnitParamsRunner for Mockito.verify() of different methods
因此,我有一個方法采用 Object 參數,並根據其值調用不同的方法(我只使用 if 語句而不是 switch)。
public class ClassToTest {
public void methodToTest(String input) {
if (input.equals("A")) {
ServiceClass.methodA();
}
if (input.contentEquals("B")) {
ServiceClass.methodB();
}
if (input.contentEquals("C")) {
ServiceClass.methodC();
}
}
}
public class ServiceClass {
public static void methodA() {
System.out.println("A");
}
public static void methodB() {
System.out.println("B");
}
public static void methodC() {
System.out.println("C");
}
}
我知道 JUnitParamsRunner 簡化了參數化測試的編寫,並且我知道 Mockito.verify() 來檢查是否調用了特定方法。 但在我的情況下,是否可以對不同的輸入進行參數化測試並檢查是否調用了相應的方法? 還是對於 verify() 我需要為每個場景編寫單獨的測試。
看起來您想驗證 ServiceClass 中的 static 方法。 在這種情況下, Mockito
無法幫助您,因為它無法處理 static 方法。 您可能想為此使用PowerMockito
。
這里有一個例子說明這會是什么樣子。 使用PowerMockito 2.0.4
和 mockito2 api 進行測試。
@RunWith(PowerMockRunner.class)
@PrepareForTest(ServiceClass.class)
@PowerMockRunnerDelegate(JUnitParamsRunner.class)
public class ParamsTest {
@Test
@Parameters({"A", "B", "C"})
public void test(String input) throws Exception {
PowerMockito.mockStatic(ServiceClass.class);
new ClassToTest().methodToTest(input);
PowerMockito.verifyStatic(ServiceClass.class);
switch (input) {
case "A":
ServiceClass.methodA();
break;
case "B":
ServiceClass.methodB();
break;
case "C":
ServiceClass.methodC();
break;
default:
Assert.fail();
}
}
}
驗證部分看起來相當難看,所以我不確定是否值得這樣做。
也應該可以將驗證部分作為另一個參數傳遞給測試,但這並不能真正讓它變得更好。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.