I'm testing a "save in DB" public method that also sends some of that saved data modified to a service. The test assures that it is saving what it receives but is sending the modified data different. The problem comes when an internal private method calls a repository that is set as autowired its response is nullPointer as in the reflection that autowired repository is not initialized.
So first to assert what the private method answers I made a reflection on the private method.I mocked the inside autowired service with a controlled response but found no result on how set that mocked service answer on my private reflection.
I'm still new with testing so i might have make some mistakes explaining would do my best to correct it and expand on the topic further down.
This is for a public method "X" that saves something in database(Returns a code for the thing saved) then does some other stuff and then goes to a private method "Y" to verify some data and inside that private method goes to other private method "Z" ,to create some new data retriving data from another service "B" and from what it got before, to send that to an outside service "A". All of this is done in one same class implementation "classImpl". The private method "Z" recives the same as the "X" method and it generates and returns the data that is going to be send in "A" service using what it got from "B".
@Test
@Rollback(false)
@Transactional(readOnly = false)
TEST{
testData testXData= new testData();
testXData.set()...
testXData.set()...
.......Generate data to be saved.
mockResponse controlledOutput = mock(mockResponse.class);
deliverInMockResponse deliverInMockResponse = new deliverInMockResponse();
deliverInMockResponse.set()...
deliverInMockResponse.set()...
.......Generate data to be delivered in the mockResponse.
when(controlledOutput.findByAnd(otherSomething)).thenReturn(deliverInMockResponse);
assertNotNull(testSaveMethodX(testXData));
String Something = "evalutaThis";
assertEquals(testXData.getSomething(),Something);
try{
classImpl publicImpl = new classImpl();
Method method = classImpl.class.getDeclaredMethod("Z", testData.class);
method.setAccessible(true);
methodZResponse Zoutput = (methodZResponse) method.invoke(publicImpl, testXData);
assertNotEquals(Zoutput.getSomething(),Something);
}
catch (Exception e){
assertNotNull(null);
}
}