gpt4 book ai didi

java - 模拟不保存状态

转载 作者:行者123 更新时间:2023-11-28 20:33:26 25 4
gpt4 key购买 nike

我正在使用 easymock 进行单元测试,结果未在答案对象中设置。模拟对象被传递给测试对象,并在处理后返回模拟对象的相同引用,但它不保存它的结果集。

代码应该让图片更清晰

@Test
public void test() {
DomainInterface mock = EasyMock.create("mock", DomainInterface.class);
Subject subject = new Subject();
subject.setDomainInterface(mock);

final DomainInterface domain = subject.process();

assertEquals("Not the same instance", mock, domain);

final String expected = "VALID";
final String answer = domain.getAnswer();

assertEquals("Not the expected answer", expected, answer);
}

Subject.process 正在做的是一些验证,然后将“VALID”设置为答案,但是执行失败并显示断言错误消息

java.lang.AssertionError: Not the expected answer expected:<VALID> but was:<null>

主题对象有一个 DomainInterface 类型的私有(private)成员,其中设置了模拟的引用,为什么答案在断言之前不成立?

提前致谢

最佳答案

我刚刚注意到您断言返回的是相同的模拟。您也永远不会调用 replay() 将 mock 置于重放模式 - 如果您调用过,它会在 Subject 尝试调用任何方法时立即抛出异常

我的猜测是,您期望 mock 记住对 setAnswer 的调用,并在调用 getAnswer 时以相同的结果回复- 但 mock 不是那样工作的。您可能期待调用setAnswer("VALID")。像这样:

public void test() {
DomainInterface mock = EasyMock.create("mock", DomainInterface.class);

// Expect that the subject will call setAnswer with an argument of "VALID"
mock.setAnswer("VALID");

EasyMock.replay();

Subject subject = new Subject();
subject.setDomainInterface(mock);

DomainInterface domain = subject.process();
assertEquals("Not the same instance", mock, domain);

// No need to assert the result of calling getAnswer - we've already asserted
// that setAnswer will be called.
}

就我个人而言,我正在成为许多测试的手写伪造品的粉丝 - 模拟非常适合交互测试(又名协议(protocol)测试)但在这种情况下它看起来就像一个简单的伪造一样......或者可能是一个混合,它伪造出简单的位(属性)但允许模拟需要交互测试的位。

关于java - 模拟不保存状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7248341/

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