![](/img/trans.png)
[英]Misplaced argument matcher detected here. You cannot use argument matchers outside of verification or stubbing in Mockito
[英]Mockito Repetition in Stubbing and Verification
似乎在某些情況下,EasyMock stubbing 可以代替驗證。 舉個簡單的例子:
A類:
public class A {
private B b;
public A(B b) {
this.b = b;
}
int main(int input) {
return b.timesThree(input + 4);
}
}
B類:
public class B {
int timesThree(int input) {
return input * 3;
}
}
A測試類:
@ExtendWith(MockitoExtension.class)
public class ATest {
@Mock
B b;
@InjectMocks
A a;
@Test
void testMain() {
doReturn(21).when(b).timesThree(7);
int result = a.main(3);
assertEquals(21, result);
verify(b).timesThree(7);
}
}
verify
電話有什么意義嗎? when
調用已經斷言b.timesThree()
的輸入參數為 7。
在這種情況下沒有。 這歸結為您在測試中真正想要斷言的內容。
在這里,您試圖測試當使用值 2 調用 main 方法時,應該會發生什么
應使用 value+4 調用 timesThree
從 timesThree 返回的值應該由您的主函數返回
由於在您的測試中,以下三行足以斷言上述兩種情況,因此您無需在此處進行驗證。
doReturn(21).when(b).timesThree(7);
int result = a.main(3);
assertEquals(21, result);
確定您的測試是否足夠好的最簡單方法是注釋掉您的部分實現並使您的測試失敗 (TDD)。 只要你的考試不及格,你就很好。
例如:將 4 更改為 5 - 測試失敗,刪除輸入測試失敗
假設您的 timesThree 方法沒有返回值,而是將其存儲在某處
int main(int input) {
//Stores value somwhere
b.timesThree(input + 4);
}
在這里,您的測試必須斷言 timesThree 被調用一次,值為 7。在這種情況下,您需要驗證,因為如果沒有驗證,您將永遠無法獲得失敗的測試。
同樣在旁注中,其中一條評論提到“如果代碼被 return 21 替換,則測試將通過;”
為了證明您對此的測試,請考慮使用隨機整數而不是硬編碼值。 這將確保您的實現中沒有意外的硬編碼。 隨機整數的示例庫https://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/math/RandomUtils.html#nextInt()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.