I met a following question when use jmockit.
I have an abstract class, it also has many concrete (non-abstract) instance methods, now i want to write a JUnit4 test case to verify one non-abstract & instance method of the abstract class but mock up all other methods in the class?
For example:
public class abstract Animal {
public abstract void abstractMethod1();
......
public abstract void abstractMethodN();
public void method1() {
System.out.println("Do something1 ...");
}
public void method2() {
System.out.println("Do something2 ...");
}
......
public void methodN() {
method1();
method2();
System.out.println("Do somethingN ...");
}
}
For this defined class, i want to write a JUnit4 test case to verify the logic in methodN only, so i want to mock the whole class. (for method1 and method2, mock or not mock them, either one is OK.) how to do it?
There are two ways:
public class AnimalTest
{
// Both tested and (partially) mocked:
@Tested @Mocked Animal animal;
@Test
public void testMethodNWhileMockingMethods1And2()
{
// Recorded methods will be mocked:
new Expectations() {{
animal.method1();
animal.method2();
}};
// Methods not recorded execute normally.
animal.methodN();
}
@Test
public void testMethodNWhileExecutingMethods1And2AndAlsoVerifyingTheyWereCalled()
{
animal.methodN();
// Executed methods can still be verified:
new Verifications() {{
animal.method1();
animal.method2();
}};
}
}
Note that verifying methods that were actually executed, although possible, may not be a good idea; it's best to verify whatever the methods did through more usual means.