Search code examples
javaunit-testingmockitopowermockito

Test a method without initialize the class


I'm very new to unit testing, I'm wondering if there is a way to test a method without initializing the class. The reason I'm asking is because there are lot of object passing in the constructor meaning a lot of mocking stubbing while from a thorough check methodToTest seems not to use any object attribute. It's not my code otherwise the method could be converted to static.

class ExampleClass {
   public ExampleClass(FirstClass fc, SecondClass sc, ThirdClass tc) {}

   public void methodToTest(FourthClass foc) {}
}

Solution

  • Ok, it seems I found a way. Since the method is irrelevant to the state of the object, I could mock the object and order the MockRunner to use the real method when it is called. It is named partial mocking. The way of doing it is

        ExampleClass = PowerMockito.mock(ExampleClass.class);
        when(ExampleClass.methodToTest(foc)).thenCallRealMethod();