0

I end up with my repository as null when testing a method in a service class. It is unclear what causes this for me. In my service class I make use of a private RestTemplate that I setup as follows together with repository as @Mocks and service class @Injectmocks on :

...
 @InjectMocks
    @Spy
    WorkService workService;

    @Mock
    private WorkJobRepository workJobRepository;
...

    @Mock
    RestTemplateBuilder mockedBuilder= Mockito.mock(RestTemplateBuilder.class);
    @Mock
    RestTemplate mockedRestTemplate = Mockito.mock(RestTemplate.class);

    @BeforeEach
    void setUp() {
        ReflectionTestUtils.setField(listToPrintService, "restTemplate", mockedRestTemplate);

    }

My test case in which repository is not passed (it is null):

@Test
    void testGetRequestListToWork() {
        ListToWork listToWork = getListToWork();
        WorkJob WorkJob = getOneWorkJob();

        ResponseEntity<String> responseEntity = getOneResponseEntityString(listToWork);

        Mockito.doReturn(responseEntity).when(listToWorkService).getRequestListToWork(listToWork);

        Mockito.when(listToWorkService.getRequestListToWork(listToWork)).thenAnswer(new Answer<ResponseEntity<String>>() {
            @Override
            public ResponseEntity<String> answer(InvocationOnMock invocation) {
                return responseEntity;
            }
        });
        String json = responseEntity.getBody().toString();

        Mockito.when(listToWorkService.createNewWorkJob(json, listToWork)).thenReturn(WorkJob);
        listToWorkService.getRequestListToWork(WorkJob);


        assertEquals("xxx", repository.getById(listToWork.getId));
    }

Here's the method I am trying to test:

public WorkJob getRequestListToWork(WorkJob WorkJob) {
        ListToWork listToWork = new ListToWork(WorkJob.getTemplateId(), WorkJob.getStoreName(), WorkJob.getJobListId(), WorkJob.getId());
        ResponseEntity<String> responseEntity = getRequestListToWork(listToWork);
        Gson g = new Gson();
        String json = responseEntity.getBody().toString();
        WorkJob newWorkJob = createNewWorkJob(json,listToWork);
        if(newWorkJob.getJobId() != -1 && newWorkJob.getJobState() != 12) {
            pollForJobStatus(newWorkJob);
        }
        return newWorkJob;
    }

Can anybody advise? What is causing the repository not to be passed?

CompileNow
  • 79
  • 14
  • Your method isn't using your repository. But if I had to guess, I'd say it's one of the reasons described in [Why is my class not calling my mocked methods in unit test?](https://stackoverflow.com/q/74027324/112968) – knittl Nov 23 '22 at 21:15

0 Answers0