这不是Test class with a new() call in it with Mockito的重复。我正在尝试编写一个测试来验证在我的间谍对象(mockToyFacade)的构造函数中是否正在调用某些方法。
受测试的类是ToyFactoryFacade。客户的想法是与ToyFactoryFacade(包装ToyFactory)交互以生成ToyFacades,它本身就是玩具对象的包装。
我想验证是否在ToyFacade上调用 addToyName(toyName)和 addCreationTime(creationTimestamp)。这两种方法都在ToyFacade的构造函数中调用。
当我试图监视ToyFacade,并验证上述方法都被调用时,我收到一个错误,其中显示“实际上,与此模拟没有交互。”当我打电话给方法分开(即,不通过构造函数),验证检查正确。 我不确定我做错了什么。
public class ToyFactoryFacadeTest {
private Toy mockToy;
private ToyFacade mockToyFacade;
// System under test.
private ToyFactoryFacade toyFactoryFacade;
private ToyFactory mockToyFactory;
@Before
public void setup() {
mockToy = mock(Toy.class);
mockToyFacade = spy(new ToyFacade(mockToy, "Phone", System.currentTimeMillis()));
mockToyFactory = mock(ToyFactory.class);
toyFactoryFacade = new ToyFactoryFacade(mockToyFactory) {
@Override
public Toy getToyFacade(String toyName, long creationTimestamp){
return mockToyFacade;
}
};
}
@Test
public void testToyFactoryFacade() {
toyFactoryFacade.initializeAndGetToy("Phone", System.currentTimeMillis());
verify(mockToyFacade).addToyName("Phone");
verify(mockToyFacade).addCreationTime(anyLong());
}
}
public class ToyFactoryFacade {
private final ToyFactory toyFactory;
public ToyFactoryFacade(ToyFactory toyFactory) {
this.toyFactory = toyFactory;
}
public ToyFacade initializeAndGetToy(String toyName, long creationTimestamp)
{
getToyFacade(toyName, creationTimestamp);
}
// For testing.
protected ToyFacade getToyFacade(String toyName, long creationTimestamp
{
return new ToyFacade(toyFactory.newToy(), toyName, creationTimestamp);
}
}
public class ToyFactory {
public Toy newToy() {
return new Toy();
}
}
public class ToyFacade {
private final Toy toy;
public ToyFacade(Toy toy, String toyName, long creationTimeStamp) {
this.toy = toy;
addToyName(toyName);
addCreationTime(creationTimestamp);
}
public void addToyName(String name) {
toy.addToyName(toyName);
}
public void addCreationTime(long timestamp) {
toy.addCreationTime(timestamp);
}
}
public class Toy {
public String toyName;
public String creationTimestamp;
public void addToyName(String name) {
toyName = name;
}
public void addCreationTime(long timestamp) {
creationTimestamp = timestamp;
}
}
答案 0 :(得分:1)
您的测试没有按照您的期望进行,因为在您创建间谍之前,您尝试验证的方法调用已经发生。你真正想要做的是测试这两个方法调用的效果,而不是调用本身。这看起来像
verify(mockToy).addToyName("Phone");
verify(mockToy).addCreationTime(timestamp);
其中timestamp
是您在setUp
方法中传入的内容。