[英]EasyMock @Mock is not working same as createMock for abstract classes
按照这里的答案,@Mock注解和createMock从功能视图来看是相同的。 但是,使用这些工具时我面临一个奇怪的问题。 这里的背景很少。
我必须测试从Abstractclass调用方法的ClassUnderTest。 当我应该从单元测试调用ClassUnderTest时,我希望调用Abstractclass方法。
`
public abstract AbstractClass {
public void addValue(int a, int b) {
// Invoking another method which is abstract.
};
}
public class ClassUnderTest {
public Abstractclass obj;
public ClassUnderTest(Abstractclass obj) {
// Parameterized constructor.
}
public MethodToTest(){
object.addValue(1, 2); // Calls the method.
}
}
@RunWith(EasyMockRunner.class)
public class TestFile {
@Mock
private AbstractClass concrete;
@Test
public void testMethod() {
concrete = EasyMock.createMock(AbstractClass.class);
concrete.addValue(1,2);
EasyMock.expectLastCall().once();
EasyMock.replay();
new ClassUnderTest().methodToTest();
EasyMock.verify() // The code under scan.
}
}
`我面临以下问题:
当我使用@Mock注释时,EasyMock验证会引发错误,指出未满足Abstractclass.addValue()期望。
但是,当我删除@Mock注释时,它可以正常工作,并且没有错误。
对于非抽象类,@ Mock对我来说工作正常。
有人可以解释这种行为吗?
您的实际代码必须与此代码不同。 两者的行为应完全相同。 否则,它是一个错误。 我尝试了您的代码(应用了很多修复程序。您下次应该发布正确运行的示例)。 它运作完美。 就这个
abstract class AbstractClass {
public abstract void foo();
public void addValue(int a, int b) {
foo();
}
}
class ClassUnderTest {
private AbstractClass obj;
public ClassUnderTest(AbstractClass obj) {
this.obj = obj;
}
public void methodToTest(){
obj.addValue(1, 2); // Calls the method.
}
}
@RunWith(EasyMockRunner.class)
public class TestFile {
@Mock
private AbstractClass concrete;
@Test
public void testMethod() {
// concrete = EasyMock.createMock(AbstractClass.class);
concrete.addValue(1,2);
EasyMock.replay();
new ClassUnderTest(concrete).methodToTest();
EasyMock.verify(); // The code under scan.
}
}
要超级清楚。 这4个意思完全相同 :
// 1. Calling once the void method
concrete.addValue(1,2);
// 2. Calling once the void method and then using expectLastCall()
concrete.addValue(1,2);
expectLastCall();
// 3. Calling once the void method and then expect once
concrete.addValue(1,2);
expectLastCall().once();
// 4. Calling once the void method and then expect one time
concrete.addValue(1,2);
expectLastCall().time(1);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.