I have to test a method inside some class like this:
public class aClassToTest{
private SomeService someService = new SomeService();
public String methodToTest(){
String data = someService.getData();
//....
}
}
So, I have mocked SomeService class for returning my mock-object instead of original SomeService-object. I have done it via PowerMockito in every of my @Test
method
SomeService someServiceMock = mock(SomeService.class);
when(someServiceMock.getData().thenReturn(Data myMockedData)
PowerMockito.whenNew(SomeService.class).withAnyArguments().thenReturn(someServiceMock);
And I have this annotation above my Test class:
@PrepareForTest({aClassToTest.class, SomeService.class})
It works fine if there is only one test, but if there is a few tests someServiceMock.getData()
returns data from the very first test each time dispite the fact, that i mock it in every test with new data. I've tried to add annotation @PrepareForTest({aClassToTest.class, SomeService.class})
above every @Test
method, but now I have an OutOfMemoryError
after a few tests, and now it works only if I run whole Test class with all test methods, but if I run test methods separately I have No tests found for given includes
error.
I have test class like this:
@RunWith(PowerMock.class)
@PrepareForTest({aClassToTest.class, SomeService.class})
public class TestClass{
private void doMockSomeService(String testData){
SomeService someServiceMock = mock(SomeService.class);
when(someServiceMock.getData().thenReturn(testData);
PowerMockito.whenNew(SomeService.class).withAnyArguments().thenReturn(someServiceMock);
}
@Test
public void testCase1(){
String expectedResult = "expectedResult1";
doMockSomeService("123");
ClassToTest classToTest = new ClassToTest();
String result = classToTest.methodToTest();
assertEquals(result, expectedResult);
}
@Test
public void testCase2(){
String expectedResult = "expectedResult2";
doMockSomeService("456");
ClassToTest classToTest = new ClassToTest();
String result = classToTest.methodToTest();
assertEquals(result, expectedResult);
}
}
In this case, the return value of someService.getData() is always "123".