JMock 期望 - 是否可以检查期望中的实际值?
我是 Java 和 JMock 的新手,目前正在尝试了解模拟。我用虚拟类创建了这个虚拟测试:
public class JmockUnitTest {
private Mockery context = new Mockery();
private Class2 class2 = context.mock(Class2.class);
@Test
public void testMethod() {
Class1 class1 = new Class1();
context.checking(new Expectations() {{
oneOf(class2).method2();
will(returnValue(1234));
}});
class1.method1();
}
public class Class1 {
public void method1() {
Class2 class2 = new Class2Impl();
Integer time = class2.method2();
}
}
public interface Class2 {
public Integer method2();
}
public class Class2Impl implements Class2 {
public Integer method2() {
return 10;
}
}
}
我的 Class2Impl.method2() 返回整数 10 但期望设置为 1234。测试仍然通过,所以我只是想澄清这个示例是否只是期望返回类型为任何整数?检查它是否返回 10 是否可能或者是否有意义?
谢谢
I'm new to Java and JMock and I'm currently trying to get my head around mocking. I've created this dummy test with dummy classes:
public class JmockUnitTest {
private Mockery context = new Mockery();
private Class2 class2 = context.mock(Class2.class);
@Test
public void testMethod() {
Class1 class1 = new Class1();
context.checking(new Expectations() {{
oneOf(class2).method2();
will(returnValue(1234));
}});
class1.method1();
}
public class Class1 {
public void method1() {
Class2 class2 = new Class2Impl();
Integer time = class2.method2();
}
}
public interface Class2 {
public Integer method2();
}
public class Class2Impl implements Class2 {
public Integer method2() {
return 10;
}
}
}
My Class2Impl.method2() return the integer 10 but the expectation is set to 1234. The test still passes so I just wanted to clarify does this example jus expect the return type to be any Integer? Is it possible or does it even make sense to check that it returns 10?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
问题是您没有将 Class2 的实例传递给 Class1 的实例,因此无法将两个对象绑定在一起。 JMock 旨在测试对象如何协作,因此必须有一种方法来设置对象图。这可能是一个 setter 或通过构造函数。在您的情况下,如果 Class2 真的非常简单,它只返回一个值,那么可能不值得使用模拟,而是使用真实的实例。
如果您确实使用模拟,那么正如另一篇文章所说,您需要使用@RunWith(JMock.class)或assertIsSatisfied(),或者尝试版本控制中的新模拟junit规则。
The problem is that you're not passing the instance of Class2 into the instance of Class1, there's no way to bind the two objects together. JMock is designed for testing how objects collaborate, so there has to be a way to set up the graph of objects. That might be a setter or through the constructor. In your case, if Class2 really is so simple that it just returns a value, then it might not be worth using a mock but using a real instance.
If you do use a mock, then as the other post says, you need to use @RunWith(JMock.class), or assertIsSatisfied(), or try the new mockery junit rule that's in the version control.
添加
到测试的末尾。这将使 JMock 确认您定义的所有期望均得到满足。
Add
to the end of your test. This will have JMock confirm all the expectations you defined were met.