简体   繁体   中英

How to use jmockit to mock a whole abstract class but exclude one or several methods that should be verified within one JUnit4 test case?

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.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM