Search code examples
javatestingmockingpowermockpowermockito

Anyway to create a Test Helper class that creates mocks?


In my testing of a legacy system, I have found myself having to mock similar classes for different parts of the system I'm increasing test coverage for. I would like to create a helper class for my tests that could call a method that would set up particular mocks and their return values.

Here's an example of a method I have had to create a few times in multiple tests.

public void mockClassINeedToMockToReturn(Boolean bool){
   mockStatic(classINeedToMock.class); 
   when(classINeedToMock.getSuccess(Mockito.any(someClass.class))).thenReturn(bool);
}

I have tried setting this up in a HelperTest.class (in the same project/folder as my tests) and it isn't working. I have included both the following Annotations in the class.

@RunWith(PowerMockRunner.class)
@PrepareForTest({classINeedToMock.class})

I have tried:

  1. Using the methods statically and calling them in my tests. (does not mock)
  2. Creating a HelperTest object and calling the method in my test. (still does not mock)
  3. Having my tests Extend my HelperTest.class and calling the method from in my tests. (Still refuses to mock the class)

I'm sure this is something to do with the way the PowerMockRunner works. So is there a way to make this work? Or should I just come to terms with duplicating these methods throughout my project.


Solution

  • It's the little details.... When looking into it more I noticed the class I was mocking had 2 separate methods.

    theClass.method(var1, var2);
    theClass.method(var1, List<var2>); 
    

    One of my tests was calling the first method, the other was calling the second method. When I ran the second test (only having mocked the first method), it was calling the actual class because that method was not mocked.

    After setting up the correct mock with the proper input parameters I could call the method statically and the mock would be created and used appropriately.