How to mock RestTemplate with MockRestServiceServer? - java

#RunWith(MockitoJUnitRunner.class)
public class FeatureFlipperManagerTest {
#Autowired
RestTemplate restTemplate = new RestTemplate();
#Autowired
Service service = new Service();
MockRestServiceServer mockServer = MockRestServiceServer.createServer(restTemplate);
#Test
public void test() throws Exception {
mockServer.expect(requestTo(Mockito.anyString()))
.andRespond(withSuccess("{\"enabled\":true}", MediaType.APPLICATION_JSON));
boolean res = service.isEnabled("xxx");
mockServer.verify();
Assert.assertEquals(true, res);
}
}
I have MockRestServiceServer to mock restTemplete in a service. But it always fail. it shows the error as java.lang.AssertionError: Further request(s) expected
0 out of 1 were executed. Any one could let me know where I did not do it right.
The service itself will looks as this:
public class Service{
public boolean isEnabled(String xxx) {
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<String> response = restTemplate.getForEntity("someurl",String.class);
if(...)return true;
return false;
}
}

First of all, your Service class creates a new instance of RestTemplate on every request. I cannot stress enough how bad practice it is. Create a bean of type RestTemplate and inject it into your Service bean (it is most likely already created - depending on the Spring MVC version you are using).
Once you have it, then both RestTemplates: one in your Service bean and one injected into FeatureFlipperManagerTest will be the same and testing with MockRestServiceServer will be possible.
EDIT - to be more explicit:
Modify your Service class to:
#Component
public class Service {
private RestTemplate restTemplate;
#Autowired
public Service(RestTemplate restTemplate) {
this.restTemplate = restTemplate;
}
public boolean isEnabled(String xxx) {
ResponseEntity<String> response = restTemplate.getForEntity("someurl",String.class);
if(...)return true;
return false;
}
}
and your test class to:
#RunWith(MockitoJUnitRunner.class)
public class FeatureFlipperManagerTest {
#Autowired
RestTemplate restTemplate;
#Autowired
Service service;
MockRestServiceServer mockServer = MockRestServiceServer.createServer(restTemplate);
#Test
public void test() throws Exception {
mockServer.expect(requestTo(Mockito.anyString()))
.andRespond(withSuccess("{\"enabled\":true}", MediaType.APPLICATION_JSON));
boolean res = service.isEnabled("xxx");
mockServer.verify();
Assert.assertEquals(true, res);
}
}
If this fails with exception saying that there is no RestTemplate bean present then please paste info about version of Spring (Spring Boot?) you are using.

I think you mean you want to use RestTemplate which is provided by spring, so you should createServer after the spring autowired the RestTemplate. I think you can do it like this:
#RunWith(MockitoJUnitRunner.class)
public class FeatureFlipperManagerTest {
#Autowired
RestTemplate restTemplate;
Service service;
MockRestServiceServer mockServer;
#Before
public void init() {
service = new Service();
service.setRestTemplate(restTemplate);
// If you have autowired restTemplate in Service, you can just autowired the service
mockServer = MockRestServiceServer.createServer(restTemplate);
}
#Test
public void test() throws Exception {
mockServer.expect(requestTo(Mockito.anyString()))
.andRespond(withSuccess("{\"enabled\":true}", MediaType.APPLICATION_JSON));
boolean res = service.isEnabled("xxx");
mockServer.verify();
Assert.assertEquals(true, res);
}
}

This is not an answer to your question, but just in case anyone comes across this question in 2021… With Spring Boot Testing, you may want to take advantage of testing the REST slice only with #RestClientTest. This creates a RestTemplateBuilder bean only by default, if you want an auto-wired RestTemplate just add one bit of configuration as below. (The example is in Kotlin, using Java instead remains as an excercise to the reader.)
#AutoConfigureWebClient(registerRestTemplate = true)
#RestClientTest(Service::class)
class AdkClientTest #Autowired constructor(
private val mockRestServiceServer: MockRestServiceServer,
private val service: Service
) {
// …
}

Related

Understanding #MockBean usage With 'RestTemplate restTemplate'

The behavior that I am seeing is a NullPointerException in the second test when the mocked restTemplate called. That pointed to a problem in the resetting of the mock. What surprised me is the fix ( that made both tests pass).
Modifying the code from
#MockBean private RestTemplate restTemplate;
to
#MockBean(reset = MockReset.NONE) private RestTemplate restTemplate;
fixed the issue. A few questions here:
Why didn't the default #MockBean behavior of MockReset.RESET work?
Is there something wrong with how I have set up my test such that default MockReset.RESET was failing?
Is there something wrong with the test config class?
Hopefully, I've provided enough context to answer the question.
I've created a simplified example of what I'm seeing:
Test configuration:
#Profile("test")
#Configuration
public class TestConfiguration {
#Bean
#Primary
public ObjectNode getWeatherService(RestTemplate restTemplate) {
return new WeatherServiceImpl(restTemplate);
}
}
The test:
#SpringBootTest
#ActiveProfiles("test")
#AutoConfigureMockMvc
class SamTest {
#Autowired private MockMvc mockMvc;
#MockBean private RestTemplate restTemplate;
/*
Works:
#MockBean(reset = MockReset.NONE) private RestTemplate restTemplate;
Fails:
#MockBean(reset = MockReset.BEFORE) private RestTemplate restTemplate;
#MockBean(reset = MockReset.AFTER) private RestTemplate restTemplate;
*/
#Test
public void testOne() throws Exception {
Mockito.when(restTemplate.getForEntity("http://some.weather.api", ObjectNode.class))
.thenReturn(new ResponseEntity("{\"weather\" : \"rainy\"}", HttpStatus.OK));
// Makes call to standard #RestController with a #GetMapping
// Call to external API is contained in #Service class.
// Currently controller just passes through the json from the underlying service call.
this.mockMvc.perform(
get("/weather/check").
contentType(MediaType.APPLICATION_JSON_VALUE)).
andExpect(status().isOk());
}
#Test
public void testTwo() throws Exception {
Mockito.when(restTemplate.getForEntity("http://some.weather.api", ObjectNode.class))
.thenReturn(new ResponseEntity("{\"error\" : \"bandwidth\"}", HttpStatus.BANDWIDTH_LIMIT_EXCEEDED));
this.mockMvc.perform(
get("/weather/check").
contentType(MediaType.APPLICATION_JSON_VALUE)).
andExpect(status().is5xxServerError());
}
}
The service:
#Service
public class WeatherServiceImpl implements WeatherService {
private final RestTemplate restTemplate;
#Autowired
public WeatherServiceImpl(RestTemplate restTemplate) {
this.restTemplate = restTemplate;
}
#Override
public ObjectNode retrieve(URI uri) {
ResponseEntity<ObjectNode> response = restTemplate.getForEntity(uri, ObjectNode.class);
return response.getBody();
}
}
There is a misunderstanding about the #MockBean default behaviour:
Why didn't the default #MockBean behavior of MockReset.RESET work? Is
there something wrong with how I have set up my test such that default
MockReset.RESET was failing?
From the MockBean.reset method documentation:
The reset mode to apply to the mock bean. The default is
MockReset.AFTER meaning that mocks are automatically reset after each
test method is invoked.
So your MockBean will be reset and unregistered from the application context after your first testcase execution and then your second testcase will find it null, while it will not happen in case of #MockBean(reset = MockReset.NONE) as you have done.

JUnit | MockServer | RestTemplate

I have one service called PostService, which has instance variable called connectionManager Autowired.
Inside this connectionManager there is a one instance variable called restTemplate Autowired.
And in the configuration java file, object of RestTemplate is created with some logic.
When I write a test case around it, and create a MockRestServiceServer with an expected URL and post method, and in return expect a response with some body. and when I execute a test case I don't get mocked response from this mockedRestServiceServer.
As much, I can sense, this is because during test execution, a real object of rest template is created and mock server is not used to send mocked response.
can someone help me, how to overcome from this ?
class PostServie {
#Autowired
private ConnectionManager connectionManager;
public void postMessage(String msg) {
// some logic
}
}
#Component
class ConnectionManager {
#Autowired
private RestTemplate restTemplate;
public String getToken(){
ResponseEntity<String> response = this.restTemplate.postForEntity(url, request, String.class);
//returns response.body() in string format
}
}
#Configuration
class Configuration {
#Bean
public RestTemplate getRestTemplate(){
// some logic and returns object of RestTemplate
}
}
#RunWith(SpringRunner.class)
class PostServiceTest {
#Autowired
private PostMessageService postMessageService;
#Resource(name="authServerRestTemplet")
private RestTemplate authServerRestTemplet;
private MockRestServiceServer mockedAuthServerRestTemplet;
private final String requestToAuthServer ="grant_type=client_credentials&client_id=ceapiClientId";
#Before
public void setUp() {
mockedAuthServerRestTemplet =
MockRestServiceServer.createServer(authServerRestTemplet);
}
#Test
public void postServeiceSuccess () {
mockedAuthServerRestTemplet.expect(requestTo(ACCESS_TOKEN_URI)).andExpect(content().string(requestToAuthServer)).andExpect(method(HttpMethod.POST)).andRespond(withSuccess("{abc : 'abc'}", MediaType.APPLICATION_JSON));
postMessageService.postMessage(jsonMessage);
}
}
}
You're creating an instance of RestTemplate but not using it. What is MockRestServiceServer doing?
I can also see a wrong utilisation of #Resource and #Autowired, which you shouldn't specify in your test. Try use #MockBean.
Autowiring works so that the resource you create in your test is injected in the real class, not the other way round.
I'll just add some sample code here, which might help you achieve your goal.
#RunWith(SpringRunner.class)
#WebMvcTest
public abstract class AbstractControllerTest {
#Autowired
protected MockMvc mockMvc;
#MockBean
protected Service service;
#Before
public void setUp() {
Mockito.reset(service);
}
}
and then your test
public class YourTest extends AbstractControllerTest {
#Test
public void shouldDoSomething() throws Exception {
// given
List<someStuff> stuff = new ArrayList<>();
stuff.add(new Whatever("content", "John Smith");
// when - service is in the abstract controller!
when(service.getSomething()).thenReturn(stuff);
// then
mockMvc.perform(get("/posts/1/whatever").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(jsonPath("$[0].content", is("content")))
.andExpect(jsonPath("$[0].author", is("John Smith"))));
}

Spring Boot mocking other rest clients when testing

I'm consuming a remote api in my Spring MVC project using RestTemplate. One client is for authentication named LoginApiClient and I have to use this in all other rest clients.
This one my rest client that uses LoginApiClient and consumes QrCode Api.
#Service
public class QrKeyApiClient implements QrKeyApiClientBase {
private RestTemplate restTemplate;
#Autowired
private LoginApiClientBase loginApiClient;
public QrKeyApiClient(RestTemplateBuilder builder) {
restTemplate = builder.build();
restTemplate.setErrorHandler(new ErrorHandler());
}
//Other implementation details
}
And this is LoginApiClient
#Service
public class LoginApiClient implements LoginApiClientBase {
private RestTemplate restTemplate;
public LoginApiClient(RestTemplateBuilder builder) {
restTemplate = builder.build();
restTemplate.setErrorHandler(new ErrorHandler());
}
//Other implementation details
}
My unit test class for QrKeyApiClient is like below.
#RunWith(SpringRunner.class)
#RestClientTest({QrKeyApiClient.class})
#Category(IUnitTest.class)
public class QrKeyApiClientTest {
#Value("${getQrCodeUrl}")
private String getQrCodeUrl;
#Mock
LoginApiClient loginApiClient;
#Autowired
private MockRestServiceServer server;
#InjectMocks
private QrKeyApiClient client;
#Test
public void getQrCodeAsImage_makesTrueCallToApi() throws Exception {
ResponseEntity<String> responseEntity = mock(ResponseEntity.class);
HttpEntity requestEntity = new HttpEntity<>(qrCodeGenerateRequest,new HttpHeaders());
this.server
.expect(requestTo(this.getQrCodeUrl))
.andExpect(method(HttpMethod.POST))
.andRespond(withSuccess("successResult", MediaType.TEXT_PLAIN));
String qrImage = this.client.getQrCodeAsImage(qrCodeGenerateRequest);
server.verify();
assertThat(qrImage, is(notNullValue(String.class)));
}
}
I'm not sure this is the right way to do this but I want to mock my LoginApiClient in this test and inject it to QrKeyApiClient. But my test not passes with an error that says "Error creating bean with name 'qrKeyApiClient': Unsatisfied dependency expressed through field 'loginApiClient';"
So how I can test this client with mock of other clients that member of it.
It seems the problem is a mixed usage of Spring and Mockito annotations. Spring provides the #MockBean annotation to mock services in the application context.
Try replacing #Mock with #MockBean and #InjectMocks with #Autowired. The requestEntity and responseEntity are not needed then probably.
#RunWith(SpringRunner.class)
#RestClientTest({QrKeyApiClient.class})
#Category(IUnitTest.class)
public class QrKeyApiClientTest {
#Value("${getQrCodeUrl}")
private String getQrCodeUrl;
#MockBean
LoginApiClient loginApiClient;
#Autowired
private MockRestServiceServer server;
#Autowired
private QrKeyApiClient client;
#Test
public void getQrCodeAsImage_makesTrueCallToApi() throws Exception {
this.server
.expect(requestTo(this.getQrCodeUrl))
.andExpect(method(HttpMethod.POST))
.andRespond(withSuccess("successResult", MediaType.TEXT_PLAIN));
String qrImage = this.client.getQrCodeAsImage(qrCodeGenerateRequest);
server.verify();
assertThat(qrImage, is(notNullValue(String.class)));
}
}

Spring Boot Integration Test with WireMock and Eureka fails with "No instances available"

When writing an integration test for a Spring Boot application (Service A) that uses a RestTemplate (and Ribbon under the hood) and Eureka to resolve a Service B dependency, I get a "No instances available" exception when calling the Service A.
I try to mock the Service B away via WireMock, but I don't even get to the WireMock server. It seems like the RestTemplate tries to fetch the Service instance from Eureka, which doesn't run in my test. It is disabled via properties.
Service A calls Service B.
Service discovery is done via RestTemplate, Ribbon and Eureka.
Does anyone have a working example that includes Spring, Eureka and WireMock?
I faced the same problem yesterday and for the sake of completeness here is my solution:
This is my "live" configuration under src/main/java/.../config:
//the regular configuration not active with test profile
#Configuration
#Profile("!test")
public class WebConfig {
#LoadBalanced
#Bean
RestTemplate restTemplate() {
//you can use your regular rest template here.
//This one adds a X-TRACE-ID header from the MDC to the call.
return TraceableRestTemplate.create();
}
}
I added this configuration to the test folder src/main/test/java/.../config:
//the test configuration
#Configuration
#Profile("test")
public class WebConfig {
#Bean
RestTemplate restTemplate() {
return TraceableRestTemplate.create();
}
}
In the test case, I activated profile test:
//...
#ActiveProfiles("test")
#RunWith(SpringRunner.class)
#SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class ServerCallTest {
#Autowired
private IBusiness biz;
#Autowired
private RestTemplate restTemplate;
private ClientHttpRequestFactory originalClientHttpRequestFactory;
#Before
public void setUp() {
originalClientHttpRequestFactory = restTemplate.getRequestFactory();
}
#After
public void tearDown() {
restTemplate.setRequestFactory(originalClientHttpRequestFactory);
}
#Test
public void fetchAllEntries() throws BookListException {
MockRestServiceServer mockServer = MockRestServiceServer.createServer(restTemplate);
mockServer
.andExpect(method(HttpMethod.GET))
.andExpect(header("Accept", "application/json"))
.andExpect(requestTo(endsWith("/list/entries/")))
.andRespond(withSuccess("your-payload-here", MediaType.APPLICATION_JSON));
MyData data = biz.getData();
//do your asserts
}
}
This is what I done in my project:
Somewhere in your project configuration:
#LoadBalanced
#Bean
public RestTemplate restTemplate(RestTemplateBuilder builder) {
RestTemplate restTemplate = builder.build();
restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
return restTemplate;
}
#Bean
public SomeRestClass someRestClass () {
SomeRestClass someRestClass = new SomeRestClass (environment.getProperty("someservice.uri"), restTemplate(new RestTemplateBuilder()));
return parameterRest;
}
And SomeRestClass:
public class SomeRestClass {
private final RestTemplate restTemplate;
private final String someServiceUri;
public LocationRest(String someServiceUri, RestTemplate restTemplate) {
this.someServiceUri= someServiceUri;
this.restTemplate = restTemplate;
}
public String getSomeServiceUri() {
return locationUri;
}
public SomeObject getSomeObjectViaRest() {
//making rest service call
}
}
And Test class for SomeRestClass:
#RunWith(SpringRunner.class)
#RestClientTest(SomeRestClass.class)
public class SomeRestClassTest {
#Autowired
private SomeRestClass someRestClass;
#Autowired
private MockRestServiceServer server;
#Test
public void getSomeObjectViaRestTest() throws JsonProcessingException {
SomeResponseObject resObject = new SomeResponseObject();
ObjectMapper objectMapper = new ObjectMapper();
String responseString = objectMapper.writeValueAsString(resObject);
server.expect(requestTo(locationRest.getSomeServiceUri() + "/some-end-point?someParam=someParam")).andExpect(method(HttpMethod.POST))
.andRespond(withStatus(HttpStatus.OK).contentType(MediaType.APPLICATION_JSON_UTF8).body(responseString));
someRestClass.getSomeObjectViaRest();
}
}
Note: I diasbled eureka client because otherwise you have to mock a eureka server. So I added eureka.client.enabled=false in test application.properties
Hopefully this can help someone. I was getting the same error with Ribbon, but without Eureka.
What helped me was
1) Upgrading to the latest version of WireMock (2.21) in my case
2) Adding a wiremock rule stub for url "/" to answer Ribbon's ping
If you are using Eureka just bypass in test/application.properties using eureka.client.enabled=false

Inject mock into Spring MockMvc WebApplicationContext

I'm working to test (via JUnit4 and Spring MockMvc) a REST service adapter using Spring-boot. The adapter simply passes along requests made to it, to another REST service (using a custom RestTemplate) and appends additional data to the responses.
I'd like to run MockMvc tests to perform controller integration tests, but want to override the RestTemplate in the controller with a mock to allow me to predefine the 3rd party REST response and prevent it from being hit during each test. I've been able to accomplish this by instantiating a MockMvcBuilders.standAloneSetup() and passing it the controller to be tested with the mock injected as listed in this post (and my setup below), however I am not able to do the same using MockMvcBuilders.webAppContextSetup().
I've been through a few other posts, none of which answer the question as to how this might be accomplished. I would like to use the actual Spring application context for the tests instead of a standalone to prevent any gaps as the application is likely to grow.
EDIT: I am using Mockito as my mocking framework and am trying to inject one of its mocks into the context. If this isn't necessary, all the better.
Controller:
#RestController
#RequestMapping(Constants.REQUEST_MAPPING_PATH)
public class Controller{
#Autowired
private DataProvider dp;
#Autowired
private RestTemplate template;
#RequestMapping(value = Constants.REQUEST_MAPPING_RESOURCE, method = RequestMethod.GET)
public Response getResponse(
#RequestParam(required = true) String data,
#RequestParam(required = false, defaultValue = "80") String minScore
) throws Exception {
Response resp = new Response();
// Set the request params from the client request
Map<String, String> parameters = new HashMap<String, String>();
parameters.put(Constants.PARAM_DATA, data);
parameters.put(Constants.PARAM_FORMAT, Constants.PARAMS_FORMAT.JSON);
resp = template.getForObject(Constants.RESTDATAPROVIDER_URL, Response.class, parameters);
if(resp.getError() == null){
resp.filterScoreLessThan(new BigDecimal(minScore));
new DataHandler(dp).populateData(resp.getData());
}
return resp;
}
}
Test class:
#RunWith(SpringJUnit4ClassRunner.class)
#WebAppConfiguration
#SpringApplicationConfiguration(classes = MainSpringBootAdapter.class)
#TestPropertySource("/application-junit.properties")
public class WacControllerTest {
private static String controllerURL = Constants.REQUEST_MAPPING_PATH + Constants.REQUEST_MAPPING_RESOURCE + compressedParams_all;
private static String compressedParams_all = "?data={data}&minScore={minScore}";
#Autowired
private WebApplicationContext wac;
private MockMvc mockMvc;
#InjectMocks
private Controller Controller;
#Mock
private RestTemplate rt;
#Value("${file}")
private String file;
#Spy
private DataProvider dp;
#Before
public void setup() throws Exception {
dp = new DataProvider(file);
MockitoAnnotations.initMocks(this);
this.mockMvc = MockMvcBuilders.standaloneSetup(controller).build();
}
#Test
public void testGetResponse() throws Exception {
String[] strings = {"requestData", "100"};
Mockito.when(
rt.getForObject(Mockito.<String> any(), Mockito.<Class<Object>> any(), Mockito.<Map<String, ?>> any()))
.thenReturn(populateTestResponse());
mockMvc.perform(get(controllerURL, strings)
.accept(Constants.APPLICATION_JSON_UTF8))
.andDo(MockMvcResultHandlers.print());
Mockito.verify(rt, Mockito.times(1)).getForObject(Mockito.<String> any(), Mockito.<Class<?>> any(), Mockito.<Map<String, ?>> any());
}
private Response populateTestResponse() {
Response resp = new Response();
resp.setScore(new BigDecimal(100));
resp.setData("Some Data");
return resp;
}
}
Spring's MockRestServiceServer is exactly what you're looking for.
Short description from javadoc of the class:
Main entry point for client-side REST testing. Used for tests that involve direct or indirect (through client code) use of the RestTemplate. Provides a way to set up fine-grained expectations on the requests that will be performed through the RestTemplate and a way to define the responses to send back removing the need for an actual running server.
Try to set up your test like this:
#WebAppConfiguration
#ContextConfiguration(classes = {YourSpringConfig.class})
#RunWith(SpringJUnit4ClassRunner.class)
public class ExampleResourceTest {
private MockMvc mockMvc;
private MockRestServiceServer mockRestServiceServer;
#Autowired
private WebApplicationContext wac;
#Autowired
private RestOperations restOperations;
#Before
public void setUp() throws Exception {
mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
mockRestServiceServer = MockRestServiceServer.createServer((RestTemplate) restOperations);
}
#Test
public void testMyApiCall() throws Exception {
// Following line verifies that our code behind /api/my/endpoint made a REST PUT
// with expected parameters to remote service successfully
expectRestCallSuccess();
this.mockMvc.perform(MockMvcRequestBuilders.get("/api/my/endpoint"))
.andExpect(status().isOk());
}
private void expectRestCallSuccess() {
mockRestServiceServer.expect(
requestTo("http://remote.rest.service/api/resource"))
.andExpect(method(PUT))
.andRespond(withSuccess("{\"message\": \"hello\"}", APPLICATION_JSON));
}
}
Here's another solution. Simply put, it just creates a new RestTemplate bean and overrides the one already registered.
So while it performs produces the same functionality as #mzc answer, it allows me to use Mockito to craft the response and verification matchers a bit easier.
Not that it's more than a couple lines of code, but it also prevents from having to add additional code to convert from the Response object to a string for the above mockRestServiceServer.expect().andRespond(<String>) method's arg.
#RunWith(SpringJUnit4ClassRunner.class)
#WebAppConfiguration
#SpringApplicationConfiguration(classes = MainSpringBootAdapter.class)
#TestPropertySource("/application-junit.properties")
public class WacControllerTest {
private static String Controller_URL = Constants.REQUEST_MAPPING_PATH + Constants.REQUEST_MAPPING_RESOURCE + compressedParams_all;
#Configuration
static class Config {
#Bean
#Primary
public RestTemplate restTemplateMock() {
return Mockito.mock(RestTemplate.class);
}
}
#Autowired
private WebApplicationContext wac;
private MockMvc mockMvc;
#InjectMocks
private Controller Controller;
#Mock
private RestTemplate rt;
#Value("${file}")
private String file;
#Spy
private DataProvider dp;
#Before
public void setup() throws Exception {
dp = new DataProvider(file);
MockitoAnnotations.initMocks(this);
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
this.rt = (RestTemplate) this.wac.getBean("restTemplateMock");
}
#Test
public void testGetResponse() throws Exception {
String[] strings = {"request", "100"};
//Set the request params from the client request
Map<String, String> parameters = new HashMap<String, String>();
parameters.put(Constants.PARAM_SINGLELINE, strings[0]);
parameters.put(Constants.PARAM_FORMAT, Constants.PARAMS_FORMAT.JSON);
Mockito.when(
rt.getForObject(Mockito.<String> any(), Mockito.<Class<Object>> any(), Mockito.<Map<String, ?>> any()))
.thenReturn(populateTestResponse());
mockMvc.perform(get(Controller_URL, strings)
.accept(Constants.APPLICATION_JSON_UTF8))
.andDo(MockMvcResultHandlers.print());
Mockito.verify(rt, Mockito.times(1)).getForObject(Mockito.<String> any(), Mockito.<Class<?>> any(), Mockito.<Map<String, ?>> any());
}
private Response populateTestResponse() {
Response resp = new Response();
resp.setScore(new BigDecimal(100));
resp.setData("Some Data");
return resp;
}
}
org.springframework.boot.test.mock.mockito.MockBean #MockBean helped me out.

Categories