gpt4 book ai didi

java - Mockito:监视构造函数内的调用 (Java)

转载 作者:行者123 更新时间:2023-12-02 12:19:29 24 4
gpt4 key购买 nike

这不是 Test class with a new() call in it with Mockito 的重复项。我正在尝试编写一个测试来验证是否在我的 spy 对象 (mockToyFacade) 的构造函数中调用了某些方法。

被测试的类是ToyFactoryFacade。这个想法是客户端与 ToyFactoryFacade(它包装了 ToyFactory)交互以生成 ToyFacades,ToyFacades 本身是 Toy 对象的包装器。

我想用 Mockito 验证什么?

我想验证 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;
}
}

最佳答案

您的测试没有按照您的预期进行,因为您尝试验证的方法调用在您创建 spy 之前已经发生。您真正想做的是测试这两个方法调用的效果,而不是调用本身。这看起来像

verify(mockToy).addToyName("Phone");
verify(mockToy).addCreationTime(timestamp);

其中 timestamp 是您在 setUp 方法中传入的任何内容。

关于java - Mockito:监视构造函数内的调用 (Java),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45898462/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com