当我运行Junit测试时,Shuffletest,我得到了响应,"想要但没有调用:Shuffler.shuffle();"我已经看到这个问题很多次,但是据我所知,我正在做这些答案。我正在将界面实例化作为模拟,并将其注入我的甲板课上。为什么不被调用?
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));
}
}
您正在创建两个独立的调整对象。尝试从createFullDeck
方法中删除shuffler = mock(Shuffler.class);
,因为shuffler
已通过。