当我运行JUnit测试,ShuffleTest时,我收到响应,“通缉但未调用: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));
}
}
答案 0 :(得分:3)
您正在创建两个单独的shuffler对象。尝试从shuffler = mock(Shuffler.class);
方法中删除createFullDeck
,因为shuffler
在传入时已经是模拟。