0

Following are the 2 classes defined as:

Class1{
   public method1
    {
        class2.getInstance().method2();
    }
}

Class2{
   public static getInstance() { .... }

   public method2() { .... }

   public Class3 obj = new Class3();
}

I need to write junit test for method1 of class1. But I need to know how can I mock getInstance() and method2() of class2.

Also, please tell me how can I mock object of Class3.

Vishwanath
  • 149
  • 2
  • 14

3 Answers3

1

If you find it hard to write a good test for your class, you should redesign your class for better testability, that's the reason TDD is also called Test Driven Design. It should never be difficult to write a test for a simple class.

However,

Community
  • 1
  • 1
Gerald Mücke
  • 10,724
  • 2
  • 50
  • 67
0

For this task (e.g. mocking new) you need another framework. For example PowerMock.

Wavemaster
  • 1,794
  • 16
  • 27
0

So man, guys which already answered you are right.

If you find it hard to write a good test for your class, you should redesign your class for better testability, that's the reason TDD is also called Test Driven Design. It should never be difficult to write a test for a simple class.

However,

how to mock static methods is described here PowerMockito mock single static method and return object (thanks to Jorge) how to partially mock a class is already described here: How to mock a call of an inner method from a Junit

I can add following:

If you really have good reasons to do what you want I advice you further:

You can use Whitebox.setInternalState() method of powermock library in order to mock object of Class3.

Whitebox.setInternalState(class2, "obj", class3Mock);
Alex
  • 139
  • 2
  • 8