As per the answer here , @Mock annotation and createMock are same from functionality view. But, I am facing a strange issue while using these. Little background here.
I have to test ClassUnderTest which calls method from Abstractclass. When I should call from the unit test to ClassUnderTest, I expect the Abstractclass method to be called.
`
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.
}
}
` I am facing these issues:
When I am using @Mock annotation, EasyMock verify throws an error saying Abstractclass.addValue() expectation is not fulfilled.
But, when I remove @Mock annotation, it works fine and no error is there.
For Non abstract classes, @Mock is working fine for me.
Could anybody please explain this behavior?
Your real code must be different from this one. Both should behave exactly the same. Otherwise it is a bug. I tried your code (applying a lot of fixes. You should post correctly running examples next time). It works perfectly. Here is it
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.
}
}
To be super clear. These 4 mean exactly the same thing:
// 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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.