I'm using spring framework and testing with Junit and mockito.
Right now I have a method in my service which is using a few objects I create in the test, let's call them configObject1 and configObject2, I send them to the method as a parameter, and then the method start making some calls to another repositories along those configuration objects, those repositories are mocked and work well, the method makes a List of "CalculusResult" from those queries/configObjects. After that I use a repository extending CRUDRepository and make a saveAll(). Then it should return an iterable with the entities, but for some reason after the saveAll method it returns an empty list.
Test:
@Test
...
configObject1 conf1 = new configObject1 (...);
configObject2 conf2 = new configObject2 (...);
Calculusresult calcRes = new CalculusResult(null,...,new java.sql.Date(system.currentTimeMilis()),...);
List<CalculusResult> resList= new ArrayList<CalculusResult>();
resList.add(calcRes);
Calculusresult calcRes2 = new CalculusResult(1,...,new java.sql.Date(system.currentTimeMilis()),...);
List<CalculusResult> resList2= new ArrayList<CalculusResult>();
resList2.add(calcRes2);
when(calculusResultRepository.saveAll(resList)).thenReturn(resList2);
...
assertTrue(!response.isEmpty())
Method from the service:
...//The method is building the list of calculusResults
resCalc.setDate(new java.sql.Date(system.currentTimeMilis()))
resList.add(calcres);//CalculusResult object is added to the list, this object is well made
List<CalculusResult> savedResults = (List<CalculusResult>) calculusResultRepository.saveAll(resList); //This returns an empty list (If I don't cast, it also returns nothing)
for(CalculusResult calcres : savedResults){
... //This makes nothing because savedResults is empty, making the response empty and failing the test.
Repository:
@Repository
public interface CalculusResultRepository extends CrudRepository<CalculusResult, Long> {
}
I'm not sure but I think the problem may be that the object I'm creating in the test is different to the one in the service because one of the attributes is an sql Date of the moment it's created, so maybe it's not triggering "when(calculusRepository.saveAll(reslist)..." in the test because the object created in the test and the one created in the service have different Dates in that atribute.
If that's the case, is there a way to fix it? Or is the problem a completely different thing?
CodePudding user response:
You can use Mockito ArgumentMatchers to match any argument.
when(calculusResultRepository.saveAll(Mockito.any(List.class))).thenReturn(resList2);