Virat
Virat

Reputation: 581

Unit testing in java using mockito and powermockito

I have a method

public TaskProperty addTask()
{
     /*some operations
     *
     */
     mapToProperty();
 }

private TaskProperty mapToProperty()
{
    /**some op's**/
}

How to write unit test case for the addTask() without allowing the control to go inside mapToProperty() method.

How to mock the private method mapToProperty()?

Upvotes: 0

Views: 262

Answers (1)

GhostCat
GhostCat

Reputation: 140457

The fact that you want to do this ... doesn't make it a good idea:

private methods represent "internal implementation" details. Excluding them from a test ... means that your test needs to know about this private method. But your tests shouldn't know anything about your private implementation details. They should not need to care.

In other words: your unit tests should only care about the public interface of your class(es). Thus: you try to write all your code in a way that you can test those public methods without the need to "disable" something other in the class you are testing. Meaning: either try to rewrite your private method so that you can call it from any unit test; or if that is not possible, move the corresponding behavior into another class; and then provide a mocked instance of that class to your method under test.

Long story short: your question implies that you want to fix a "bad design" by using the "mocking framework hammer" to "massage" the symptom. But it a symptom; and the underlying problem is still there, and affects your code base. So spend your time fixing the real problem; instead of working around it!

And just in case you still prefer to mock that private method; I would rather suggest to look into a mockito spy to do that (although PowerMock also allows for such kind of test, see here)

Upvotes: 2

Related Questions