我和Mockito有点问题。
有没有可能这样做:
ClassX x = mock(ClassX.class)
when(x.methodB()).thenReturn("toto");
String result = x.methodA();
我正在使用Mockito 1.7。
我看到有一个“间谍”系统,但他们说不推荐使用它(为什么?)在我们测试的项目上...
我尝试了间谍功能,但我得到了一个奇怪的行为。
检查我想要做什么:
真实代码:
String methodA(String arg) {
return this.methodB(arg);
}
String methodB(String arg) {
return "toto";
}
测试代码:
@Test
public void testTest() {
final ClassX x = spy( new ClassX() );
final String argument = "arg";
doReturn("good").when(helper).methodB(argument);
assertTrue( x.methodB(argument).equals("good") );
assertTrue( x.methodA(argument).equals("good") );
}
正如他们所说的,我避免了when thenReturn语法,这对于间谍来说可能是一个问题(但无论如何它也不起作用)
奇怪的是: assertTrue( x.methodB(参数).equals(“good”) );是OK的
只有第二个参数(x.methodA(AssertTrue).equals(“good”) );不正常
实际上,helper.methodA( -> )返回"toto“模拟结果,而不是模拟结果
在这种情况下,不可能让mockito返回"good“?当测试类调用methodB时,似乎没有问题,但是如果间谍的方法调用methodB,它就不能再工作了……
我不知道该怎么办..。对同一个类的两个方法进行单元测试,并使测试相互独立,以至于著名的模拟测试框架无法实现这一基本功能,这是一件奇怪的事情吗?这不就是我们所说的真正的单元测试吗?我不明白为什么他们说要避免在测试对象上使用间谍方法…
谢谢
发布于 2010-11-22 22:08:50
间谍与被监视的对象是不同的对象。间谍只委托被监视的对象。因此,当被监视的对象从methodA调用methodB时,它将对自己调用它,而不是对间谍调用它。
发布于 2011-01-04 04:39:17
更新:我写了下面的东西,然后片刻之后发现了.thenCallRealMethod(),它允许你有效地执行部分存根。Mockito的作者建议您使用重构将依赖项分离到不同的类中;但它们确实提供了部分存根的方法。我已经添加了一个测试方法来演示这种方法,并留下了我最初的评论。
我真的很喜欢Mockito,但这是EasyMock获胜的一个地方。我有两个不涉及Mockito的解决方案。第一种方法是覆盖测试实例上的methodB。另一种是使用EasyMock部分模拟:
import org.junit.Test;
import static org.junit.Assert.*;
import static org.easymock.EasyMock.*;
public class PartialMockTest {
class ClassX {
String methodA(String arg) {return methodB(arg);}
String methodB(String arg) {return "toto";}
}
@Test
public void MockitoOnClassX(){
ClassX classx = mock(ClassX.class);
when(classx.methodB("hiyas")).thenReturn("tomtom");
when(classx.methodA(anyString())).thenCallRealMethod();
String response = classx.methodA("hiyas");
assertEquals("tomtom",response);
}
@Test
public void OverrideOnClassX() {
ClassX classx = new ClassX(){@Override String methodB(String arg){return "tomtom";}};
String response = classx.methodA("hiyas");
assertEquals("tomtom",response);
}
@Test
public void PartialMockOnClassX() throws NoSuchMethodException {
ClassX classx = createMockBuilder(ClassX.class).addMockedMethod("methodB").createMock();
expect(classx.methodA("hiyas")).andReturn("tomtom");
replay(classx);
String response = classx.methodA("hiyas");
assertEquals("tomtom",response);
}
}
https://stackoverflow.com/questions/4246088
复制相似问题