簡體   English   中英

使用 mockito 監視數組元素返回需要但在調用該方法時未調用

[英]spying an array element with mockito returns wanted but not invoked when the method is invoked

**更新:我完全誤解了間諜 function 的方式,我應該調用一個方法的間諜版本以便驗證它不是真正的 object 方法 例如:Z4B43B0AEE35624CD931ZPget35624CD931ZPget35624CD931ZPget35624CD931B91 然后驗證(r).getPrice(); 我仍然沒有找到正確的方法來獲得我想要的東西,但我想我必須問我是否應該刪除這個問題?

我正在監視這樣的數組元素

@Test
public void testMakeCoffee_1() {
    Recipe r = spy(stubRecipies[0]);

    assertEquals(25,coffeeMaker.makeCoffee(0, 75)); // first index

            verify(r).getPrice();
});

這是 makeCoffee 方法的實現

public synchronized int makeCoffee(int recipeToPurchase, int amtPaid) {
    int change = 0;

    if (getRecipes()[recipeToPurchase] == null) {
        change = amtPaid;
    } else if (getRecipes()[recipeToPurchase].getPrice() <= amtPaid) {
        if (inventory.useIngredients(getRecipes()[recipeToPurchase])) {
            change = amtPaid - getRecipes()[recipeToPurchase].getPrice();
        } else {
            change = amtPaid;
        }
    } else {
        change = amtPaid;
    }

    return change;
}

CoffeeMaker class 中的 getRecipes() 實現

public synchronized Recipe[] getRecipes() {
    return recipeBook.getRecipes();
}

RecipeBook 是一個模擬的 class,stubRecipies 是一個數組,其中包含我要測試的自定義食譜,RecipeBook class 的 getRecipes() 是這樣存根的

recipeBookStub = mock(RecipeBook.class);
stubRecipies = new Recipe [] {recipe1, recipe2, recipe3};
when(recipeBookStub.getRecipes()).thenReturn(stubRecipies);

getRecipes() 應該返回食譜列表,因此用我的食譜 stubRecipies 數組替換它。

但是,當我在間諜 object stubRecipies[0] 的 getPrice() 方法上調用 mockito 的驗證方法時,我得到一個“想要但未調用的錯誤”,知道上面的用法返回了正確的值。

** 編輯:我嘗試手動調用 recipe1.getPrice() 仍然得到“想要但未調用錯誤”,但是當我調用 r.getPrice() 時,測試通過了,這很奇怪,因為我認為間諜 object 應該捕獲與真實 object 的交互。

因此,通過查看您的問題和評論,我建議您采取一些措施來推動這一進程。

因此,如果沒有看到整個代碼,我無法 100% 確定這是否返回了預期的 Recipe[]

public synchronized Recipe[] getRecipes() {
    return recipeBook.getRecipes();
}

您應該將模擬的 recipeBookStub 注入到 CoffeeMaker 中。

通常,在以 TDD 樣式編寫代碼時,我們從最基本的情況開始,在這種情況下,我會嘗試該方法,直到 oyu 可以讓您的方法通過:

public int makeCoffee(int recipeToPurchase, int amtPaid) { 
   getRecipes()[recipeToPurchase]getPrice();
   return 25;
}

另一個好的做法是在測試中使用盡可能少的邏輯。

而是:

Recipe r = spy(stubRecipies[0]);

嘗試:

Recipe r = spy(recipe1);

更重要的是,在 CoffeeMaker 中沒有使用間諜 object:

Recipe r = spy(stubRecipies[0]);

r 是模擬的,與您的陣列中的 object 不同,您可以通過以下方式快速證明這一點:

Assert.assertEquals(stubRecipies[0], r);
Assert.assertTrue(stubRecipies[0]== r);

assertTrue 將失敗,這意味着 stubRecipies[0] 與間諜 (r) 不同的 object

如果您將數組中的第一個索引設置為等於您的間諜 object 您可能會發現事情會更好

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM