2016-06-15 351 views
-1

當我運行JUnit測試ShuffleTest時,我得到的響應是「Wanted but not invoked:shuffler.shuffle();」 我在這個問題上看到過很多次這樣的問題,但據我所知,我正在做那些答案。我將我的界面實例化爲模擬,並將其注入到我的Deck類中。爲什麼它沒有被調用?爲什麼我的模擬方法沒有被調用?

public enum Suit { 
    SPADE("BLACK"), 
    CLUB("BLACK"), 
    HEART("RED"), 
    DIAMOND("RED"); 

    private final String color; 
    Suit(String color) { 
     this.color = color; 
    } 
} 

public enum Rank { 
    ACE, TWO, THREE, FOUR, FIVE, SIX, 
    SEVEN, EIGHT, NINE, TEN, JACK, QUEEN, KING; 

} 


public class Card { 
    private Suit suit; 
    private Rank rank; 

    public Card(Rank rank, Suit suit) { 
     this.rank = rank; 
     this.suit = suit; 
    } 

    public Suit getSuit() { 
     return suit; 
    } 

    public Rank getRank() { 
     return rank; 
    } 

    public String toString() { 
     return suit + " of " + rank + ";"; 
    } 
} 

public class Deck { 

    private List<Card> cards; 
    private Shuffler shuffler; 

    public Deck(Shuffler shuffler) { 
     this.cards = new LinkedList<Card>(); 
     this.shuffler = shuffler; 
     shuffler.shuffle(this.cards); 
     System.out.println("class " + shuffler.getClass()); 
    } 

    public void shuffle() { 
     shuffler.shuffle(this.cards); 
    } 
    public void addCard(Card card) { 
     cards.add(0, card); 
    } 

} 

public interface Shuffler { 
    public <T> void shuffle(List<T> items); 
} 
public class TestDeck { 
    private Deck deck; 
    private Shuffler mockShuffler; 

    public static Deck createFullDeck(Shuffler shuffler) { 
     shuffler = mock(Shuffler.class); 
     Deck deck = new Deck(shuffler); 
     for(Suit s : Suit.values()) { 
      for(Rank r : Rank.values()) { 
       deck.addCard(new Card(r, s)); 
      } 
     } 
     return deck; 
    } 

    @Before 
    public void before() { 
     mockShuffler = mock(Shuffler.class);   
     deck = createFullDeck(mockShuffler); 
    } 



    @Test 
    public void ShuffleTest() { 
     doAnswer(new Answer<Void>() { 
      public Void answer(InvocationOnMock invocation) throws Throwable { 
       System.out.println("Everyday I'm Shuffling"); 
       return null; 
      } 

     }).when(mockShuffler).shuffle(Matchers.anyListOf(Card.class)); 

     deck.shuffle(); 
     verify(mockShuffler, times(1)).shuffle(Matchers.anyListOf(Card.class)); 
    } 
} 

回答

3

您正在創建兩個獨立的混洗器對象。嘗試從createFullDeck方法中刪除shuffler = mock(Shuffler.class);,因爲shuffler傳入時已經是模擬。

+0

垃圾。謝謝。這是從我取代Mockito手工製作的存根之前剩下的。 – michaelAdam

+0

注意,在這個改變之後,模擬被調用2次:在Deck的構造函數中1,在調用shuffle()方法後調用1;所以測試仍然會失敗。 – Tunaki

+0

任何想法爲什麼我的問題已被downvoted? – michaelAdam

相關問題