0

I am attempting to write a unit test for a generic service class like the following:

public class ApiService{
    private RestTemplate restTemplate;

    private ServiceDao serviceDao;


    @Autowired
    public ApiService(RestTemplate restTemplate, ServiceDao serviceDao) {
        this.restTemplate = restTemplate;
        this.serviceDao = serviceDao;
    }

    public ResponseEntity getObject(ObjectRequest request) {
        // Service logic here
    }

    public ResponseEntity postObject(CreateObjectRequest request) {
        // Service logic here
    }
}

But am struggling with how to mock the restTemplate in the constructor of my service class such that when the test runs, data is not persisted.. I've looked into Mockito though don't see many examples or documentation regarding Mockito + TestNG in this context. Any help would be appreciated

azro
  • 53,056
  • 7
  • 34
  • 70
Funsaized
  • 1,972
  • 4
  • 21
  • 41

2 Answers2

0

First of all - if possible inject RestOperations in your service instead of RestTemplate. Then you will be able easily mock its behavior (note: RestTemplate implements RestOperations).

If using RestOperations is not possible - you can do something this:

RestTemplate myTemplate = Mockito.spy(new RestTemplate());
String expectedOutput = "hello mock";
String inputUrl = "https://stackoverflow.com/questions/53872148/unit-test-service-class-with-mocks-using-testng";
Mockito.doReturn(expectedOutput).when(myTemplate).getForObject(inputUrl, String.class);
String result = myTemplate.getForObject(inputUrl, String.class);
Assert.assertEquals(expectedOutput, result);
Yurii Bondarenko
  • 3,460
  • 6
  • 28
  • 47
  • That makes sense. The part I'm confused about though is how to mock this line Mockito.doReturn(expectedOutput).when(myTemplate).getForObject(inputUrl, String.class); as this getForObject call is abstracted in the dao layer (which is passed the restTemplate object in my service class) – Funsaized Dec 20 '18 at 16:44
0

I've actually constructed a method using Mockito as follows... there might be a more elegant solution so I would be interested to see:

public class ServiceTest {

    @BeforeMethod(groups="serviceTest")
    public void beforeMethod() {
        MockitoAnnotations.initMocks(this);
    }


    @Test(groups="serviceTest")
    public void testGetService_returns200() {
        when(serviceDao.getService(any(String.class), any(RestTemplate.class), any(HttpHeaders.class))).thenReturn(new ResponseEntity(new Object(), HttpStatus.OK));

        ObjectRequest request = new ObjectRequest();
        // set request values
        ResponseEntity testResponse = apiService.getObject(request);

    }
}
Funsaized
  • 1,972
  • 4
  • 21
  • 41