EasyMock expecting private method calls

20,432

Solution 1

If you find that you must mock out a private method, then you can use PowerMock.expectPrivate(). EasyMock is not capable of mocking private methods.

Solution 2

Don't do it. One of the corner stones of a good unit test is that it should rely as little as possible on implementation details. Mocking out a private method is exactly that.

Why? Because that makes your unit tests very brittle. Consider the situation where you come back to this code in a week and decide that you don't really need the method parseFoo2 and you actually want to inline its code. Or that you want to split this method into two or more smaller methods. All very valid refactoring practices- but they will break the unit test!

You don't want to be chasing unit tests each time you make a simple refactoring like that. Hence, it is considered bad practice to mock private methods.

Share:
20,432
KWJ2104
Author by

KWJ2104

Updated on February 21, 2020

Comments

  • KWJ2104
    KWJ2104 about 4 years

    Lets say I have a method that looks like this:

    public static String[] parseFoo(Foo anObject){
        Foo anotherObject = parseFoo2(anObject);
    ...
    }
    
    private static Foo parseFoo2(Foo anObject){
    ...
    }
    

    and both methods are in the same class. parseFoo2 is just a helper method that helps parseFoo get some stuff done. I'm trying to test the method parseFoo. Is there anyone in EasyMock that I can specify a return value on that private method call for parseFoo2 like the way I can specify instance method calls for an object with

    EasyMock.createMock(...);
    anObject.expect(...).andReturn(...);
    

    because I want to test the public method, but I don't want to have to go into the private method and test the implementation inside.

    Thanks