How to mock Feign Client

6.1k views Asked by At

I can't mock my Feign Client using Mockito.

MyService.class

@Service
@AllArgsConstructor
public class MyService implements IMyService{

    private static final Logger LOGGER = LoggerFactory.getLogger(MyService .class);

    private final MyRepository repository;

    private final MyFeignClient myFeignClient;

    @Autowired
    private MyDao myDao;

    @Override
    @Async
    public void process(Map<UUID, Long> command) {
        DocIds docIds = getDocIds(command.values().stream().findFirst().get());
        archiveData(command.keySet().stream().findFirst().get(), documentIds.getIds());
    }

    private DocumentIds getDocIds(Long retentionId) {
        return myFeignClient.getDocumentIds(retentionId);
    }

private void archiveData(UUID execId, List<Long> docIds) {
    List<MyDocument> myDocs= prepareMyDocs(docIds);
    repository.saveAll(myDocs);
}

And my test class:

@RunWith(SpringRunner.class)
@SpringBootTest
@ActiveProfiles("test")
public class ArchiveServiceTest {

    @Autowired
    ArchiveService archiveService;

    @MockBean
    MyDao myDao;

    @MockBean
    DocRepository archiveRepository;

    @MockBean
    private MyFeignClient myFeignClient;


    @Test
    public void shouldReturnTheSameNumberOfDocumentsToArchive() {
        //given
        List<DocData> documentData = prepareDocumentData();
//      doReturn(new DocIds()).when(myFeignClient).getDocumentIds(1000L);
        DocumentIds documentIds = new DocumentIds();
        documentIds.setIds(Arrays.asList(1L, 2L));
        when(myFeignClient.getDocIds(any())).thenReturn(documentIds);
        when(documentDataDao.getAllDocumentData(anyList())).thenReturn(documentData);
        doNothing().when(archiveRepository.saveAll(any()));

        //when
        Map<UUID, Long> command = new HashMap<>();
        command.put(UUID.randomUUID(), 1000L);

        archiveService.process(command);

        //then
        ...

MyFeignClient:

@FeignClient(name = "myFeignClient", url = "${feign.searcher.path}")
public interface MyFeignClient{

    @RequestMapping(method = RequestMethod.GET, path = "/document/path/{id}")
    DocIds getDocumentIds(@PathVariable("id") Long id);

}

When running a test,

return myFeignClient.getDocumentIds(retentionId);

returns NULL. Why? I don't have more ideas. I don't want to use WireMock. The same happens with my documentDataDao that doesn't return any values (null) specified in thenReturn() clause.

1

There are 1 answers

1
zolv On

Have You tried it this way:

Mockito.when(myFeignClient.getDocumentIds(Mockito.eq(1000L))).thenReturn(new DocIds());

In You example, mock is commented out ;)

//      doReturn(new DocIds()).when(myFeignClient).getDocumentIds(1000L);

But I'm sure it is just a bug in Your example.