I have never written a JUnit test for a Spring Boot application. My Service (localhost) calls via RestTemplate a service, which sends me a response. Can someone, please, give me a small example with my class structure? Or does anybody know a good documentation for my case?
UIController:
#RequestMapping("/my-service")
public interface MyUIController {
#RequestMapping(method=RequestMethod.GET, value= "/user", produces="application/json")
public List<User> getUser(HttpServletRequest request, HttpServletResponse response);
}
RestController:
#RestController
public class MyUIRestController implements MyUIController {
#Autowired
private MyUIService myUIService;
public List<User> getUser(HttpServletRequest request, HttpServletResponse response) {
try {
return myUIService.getUser(request, response);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
MyUIService:
#Service
public class MyUIService {
public List<User> getUser(HttpServletRequest request, HttpServletResponse response) throws IOException {
String url = this.webServiceProperties.webUserBaseURL+"searchUser";
MultiValueMap<String, String> params = new LinkedMultiValueMap<String, String>();
params.add("firstName", request.getParameter("firstName"));
UriComponents uriComponents = UriComponentsBuilder.fromHttpUrl(url).queryParams(params).build().encode();
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.setAccept(Collections.singletonList(new MediaType("application","json")));
HttpEntity<?> requestEntity = new HttpEntity<Object>(requestHeaders);
RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
ResponseEntity<List<User>> responseEntity = restTemplate.exchange(
uriComponents.toUri(),
HttpMethod.GET, requestEntity,
new ParameterizedTypeReference<List<User>>() {});
return responseEntity.getBody();
}
}
What exactly do I have to test, the service or the RestController? As you can see, I am calling another service. Do I need to make mocks or can I test my Controller/Service directly from the service, which I am calling right now?
Thanks in advance!
It is a good idea to test the RestController, by exposing the getUser() method of your MyUIRestController as an endpoint.
You can use Spring MVC Test framework to test your controllers. A simple google search for "Spring Rest Controller test" redirected me to the following links:
https://www.petrikainulainen.net/programming/spring-framework/unit-testing-of-spring-mvc-controllers-rest-api/
http://blog.zenika.com/2013/01/15/spring-mvc-test-framework/
Also you can refer to Spring Documentation below:
http://docs.spring.io/spring-security/site/docs/current/reference/html/test-mockmvc.html
Related
I am working on a non-spring application and using restTemplate feature from spring-web.While writing Junit test i am unable to mock response from restTemplate.postForEntity(). What am i doing wrong here.
Below is the function
public JsonObject apiResponse(Request request) throws JsonProcessingException {
String queryRequest = objectMapper.writeValueAsString(request);
HttpHeaders headers = new HttpHeaders();
headers.add("content-type", "application/json");
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<String> responseEntity = restTemplate.postForEntity(
"https://testurl/test/",
new HttpEntity<>(queryRequest, headers), String.class);
return JsonParser.parseString(Objects.requireNonNull(responseEntity.getBody())).getAsJsonObject();
Below is the Junit
#ExtendWith(MockitoExtension.class)
public class HandlerTest {
#Spy
#InjectMocks
Handler handler;
#Mock
RestTemplate restTemplate;
#Test
public void apiREsponseTest() throws JsonProcessingException {
//this is not working
Mockito.doReturn(new ResponseEntity <>("test", HttpStatus.OK))
.when(restTemplate).postForEntity(eq("test"), eq(HttpEntity.class), eq(String.class));
assertNotNull(handler.apiResponse(request));
RestTemplate restTemplate = new RestTemplate();
This is not getting mocked as it's a local object and it will always call the real method. You can try this to mock the restTemplate:
RestTemplate restTemplate = getRestTemplate();
protected RestTemplate getRestTemplate() {
return new RestTemplate();
}
//Add this stub to your test
when(handler.getRestTemplate()).thenReturn(restTemplate);
The URL is hardcoded here:
ResponseEntity<String> responseEntity = restTemplate.postForEntity(
"https://testurl/test/",
new HttpEntity<>(queryRequest, headers), String.class);
Hence the you need to change your stubbing as well.
Mockito.doReturn(new ResponseEntity <>("test", HttpStatus.OK))
.when(restTemplate).postForEntity(eq("https://testurl/test/"), eq(HttpEntity.class), eq(String.class));
Making these changes should make your test green hopefully. Let me know if this doesn't resolve your issue.
I am trying to get ClientHttpRequestInterceptor working following, Baeldung's Spring RestTemplate Request/Response Logging. The problem is the ClientHttpRequestInterceptor never gets called.
I had a similar issue with a HandlerInterceptor and a HandlerInterceptorAdapter interceptors. The issue was I needed a add a listener, that 99% of the article I found did not mention.
#Configuration
public class ListenerConfig implements WebApplicationInitializer {
#Override
public void onStartup(ServletContext sc) throws ServletException {
sc.addListener(new RequestContextListener());
}
}
I am guessing something about Spring has changed and the listeners are not there by default.
Does anyone know the listener for ClientHttpRequestInterceptor?
The interceptor:
public class LoggingInterceptor implements ClientHttpRequestInterceptor {
static Logger LOGGER = LoggerFactory.getLogger(LoggingInterceptor.class);
#Override
public ClientHttpResponse intercept(
HttpRequest req, byte[] reqBody, ClientHttpRequestExecution ex) throws IOException {
LOGGER.debug("Request body: {}", new String(reqBody, StandardCharsets.UTF_8));
ClientHttpResponse response = ex.execute(req, reqBody);
InputStreamReader isr = new InputStreamReader(
response.getBody(), StandardCharsets.UTF_8);
String body = new BufferedReader(isr).lines()
.collect(Collectors.joining("\n"));
LOGGER.debug("Response body: {}", body);
return response;
}
}
RestClientConfig:
#Configuration
public class RestClientConfig {
#Bean
public RestTemplate restTemplate() {
RestTemplate restTemplate = new RestTemplate();
List<ClientHttpRequestInterceptor> interceptors
= restTemplate.getInterceptors();
if (CollectionUtils.isEmpty(interceptors)) {
interceptors = new ArrayList<>();
}
interceptors.add(new LoggingInterceptor());
restTemplate.setInterceptors(interceptors);
return restTemplate;
}
}
This may be related to ClientHttpRequestInterceptor not called in springboot.
The Spring RestTemplate Interceptor, only works on the client(consumer) side or in test where the tests are acting as the client where you have a RestTemplate. I am trying to log on the server(producer) side. Thus, no need for a RestTemplate.
A Loredana with Bealdung.com was nice enough to email me and point out, I had a misconception.
Somewhere I had picked up Spring used the RestTemplate for the auto decoding and encoding of POJOs in Rest controllers. That is incorrect.
#Tashkhisi was also point to the lack a RestTempale in the commets.
I want to mock the resttemplate call which is instansiated as local variable and exchange method invoked. I mocked using expectation but it invokes the actual method . Am I missing something . Please help me on this . Thanks in advance
public class ServiceController {
public String callGetMethod (HttpServletRequest request){
String url = request.getParameter("URL_TO_CALL");
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
HttpEntity<String> entity = new HttpEntity<String>(headers);
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<String> res = restTemplate.exchange(url, HttpMethod.GET, entity, String.class);
return res.getBody();
}
}
#RunWith(JMockit.class)
public class ServiceControllerTest {
#Tested
private ServiceController controller;
#Test
public void callGetMethod (#Mocked HttpServletRequest request, #Mocked RestTemplate restTemplate){
new NonStrictExpectations() {
{
restTemplate.exchange(host,HttpMethod.GET, entity,String.class); returns (new ResponseEntity<String>("success" , HttpStatus.OK));
}
ResponseEntity<String> response = controller.callGetMethod(httpServletRequest);
}
}
We need to mock the new RestTemplate() . So that it will assign mocked object restTemplate to method local variable .
#Mocked
RestTemplate restTemplate;
new NonStrictExpectations() {
{
new RestTemplate();
result = restTemplate;
restTemplate.exchange(host, HttpMethod.GET, entity, String.class);
returns(new ResponseEntity<String>("success", HttpStatus.OK));
}
I am using spring security and it works fine, but now I want to start the security process manually, do to client changes I need to get in my controller the user name and password (the form wont call "j_spring_security_check" directly)
I thought of 2 options with both I have some problems:
After I get the parameters and do something I will send a post request to j_spring_security_check url. My code:
public void test(loginDTO loginDTO) {
MultiValueMap<String, String> body = new LinkedMultiValueMap<String, String>();
HttpHeaders headers = new HttpHeaders();
body.add(
"j_username",
loginDTO.getJ_username());
body.add(
"j_password",
loginDTO.getJ_password());
HttpEntity<?> httpEntity = new HttpEntity<Object>(
body, headers);
headers.add(
"Accept",
MediaType.APPLICATION_JSON_VALUE);
restTemplate.exchange(
"http://localhost:8080/XXX/j_spring_security_check",
HttpMethod.POST,
httpEntity,
HttpServletResponse.class);
}
This doesn't work and I get :500 internal server error why?
second option- I did the following:
public void test2(loginDTO loginDTO, HttpServletRequest request) {
UsernamePasswordAuthenticationToken token =
new UsernamePasswordAuthenticationToken(
loginDTO.getJ_username(),
loginDTO.getJ_password());
token.setDetails(new WebAuthenticationDetails(request));
Authentication authentication = this.authenticate(token);
SecurityContextHolder.getContext().setAuthentication(authentication);
this.sessionRegistry.registerNewSession(
request.getSession().getId(),
authentication.getPrincipal());
}
The problem is that onAuthenticationSuccess is not called. and it feels wrong, that I'm missing the point of using spring security.
What is the correct why?
I typically do the following:
#Controller
public class AuthenticationController
{
#Autowired
AuthenticationManager authenticationManager;
#Autowired
SecurityContextRepository securityContextRepository;
#RequestMapping(method = Array(RequestMethod.POST), value = Array("/authenticate"))
public String authenticate(#RequestParam String username, #RequestParam String password, HttpServletRequest request, HttpServletResponse response)
{
Authentication result = this.authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, password));
SecurityContextHolder.getContext.setAuthentication(result);
this.securityContextRepository.saveContext(SecurityContextHolder.getContext(), request, response);
return "successView";
}
}
The reasons for using this approach is:
Very simple, just a few lines of code if you ignore exception handling and such.
Leverages existing Spring Security components.
Uses Spring Security components configured in the application configuration and allows them to be changed as and when required. For example, the authentication may be done against an RDBMS, LDAP, web service, Active Directory, etc. without the custom code needing to worry about it.
When you want to use as most as possible from the normal Authentication Process, then you could create a mocked HttpServletRequest and HttpServletResponse (org.springframework.mock.web.MockHttpServletRequest and org.springframework.mock.web.MockHttpServletResponse) containing login and password, and then invoke
UsernamePasswordAuthenticationFilter.attemptAuthentication(
HttpServletRequest request,
HttpServletResponse response)`
afterwards you will also need to invoke SessionAuthenticationStrategy.onAuthentication(..) and successfulAuthentication(..)
This is all a bit tricky, because of private fileds, so this is my solution:
public class ExtendedUsernamePasswordAuthenticationFilter
extends UsernamePasswordAuthenticationFilter {
#Override
public void manualAuthentication(String login,
String password,
HttpServletRequest httpServletRequest)
throws IOException, ServletException {
/** I do not mock the request, I use the existing request and
manipulate them*/
AddableHttpRequest addableHttpRequest =
new AddableHttpRequest(httpServletRequest);
addableHttpRequest.addParameter("j_username", login);
addableHttpRequest.addParameter("j_password", password);
MockHttpServletResponse mockServletResponse =
new MockHttpServletResponse();
Authentication authentication = this.attemptAuthentication(
addableHttpRequest,
mockServletResponse);
this.reflectSessionStrategy().onAuthentication(
authentication,
addableHttpRequest,
mockServletResponse);
this.successfulAuthentication(addableHttpRequest,
mockServletResponse,
authentication);
}
private SessionAuthenticationStrategy reflectSessionStrategy() {
Field sessionStrategyField =
ReflectionUtils.findField(
AbstractAuthenticationProcessingFilter.class,
"sessionStrategy",
SessionAuthenticationStrategy.class);
ReflectionUtils.makeAccessible(sessionStrategyField);
return (SessionAuthenticationStrategy)
ReflectionUtils.getField(sessionStrategyField, this);
}
}
AddableHttpRequest is like a mock that is based on an real request
public class AddableHttpRequest extends HttpServletRequestWrapper {
/** The params. */
private HashMap<String, String> params = new HashMap<String, String>();
public AddableHttpRequest(HttpServletRequest request) {
super(request);
}
#Override
public String getMethod() {
return "POST";
}
#Override
public String getParameter(final String name) {
// if we added one, return that one
if (params.get(name) != null) {
return params.get(name);
}
// otherwise return what's in the original request
return super.getParameter(name);
}
public void addParameter(String name, String value) {
params.put(name, value);
}
}
An other way, would be implementing your own, authentication filter. Thats a class that invoke the AuthenticationManager.authenticate(Authentication authentication). But this class is also responsible for invoking all the stuff around authentication (what AbstractAuthenticationProcessingFilter.doFilter does)`
OK so I combined #Ralph and #manish answers and this is what I did:
(twoFactorAuthenticationFilter is an extension of UsernamePasswordAuthenticationFilter)
public void manualAuthentication(loginDTO loginDTO, HttpServletRequest request, HttpServletResponse response) throws IOException,
ServletException {
AddableHttpRequest addableHttpRequest = new AddableHttpRequest(
request);
addableHttpRequest.addParameter(
"j_username",
loginDTO.getJ_username());
addableHttpRequest.addParameter(
"j_password",
loginDTO.getJ_password());
UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) twoFactorAuthenticationFilter.attemptAuthentication(
addableHttpRequest,
response);
if (token.isAuthenticated()) {
twoFactorAuthenticationFilter.successfulAuthentication(
addableHttpRequest,
response,
null,
token);
}
}
It works fine
I have a REST controller:
#RequestMapping(value = "greeting", method = RequestMethod.GET, produces = "application/json; charset=utf-8")
#Transactional(readOnly = true)
#ResponseBody
public HttpEntity<GreetingResource> greetingResource(#RequestParam(value = "message", required = false, defaultValue = "World") String message) {
GreetingResource greetingResource = new GreetingResource(String.format(TEMPLATE, message));
greetingResource.add(linkTo(methodOn(AdminController.class).greetingResource(message)).withSelfRel());
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.add("Content-Type", "application/json; charset=utf-8");
return new ResponseEntity<GreetingResource>(greetingResource, responseHeaders, HttpStatus.OK);
}
As you can see, I'm trying hard to specify the content type returned by the controller.
It is accessed with a REST client:
public String getGreetingMessage() {
String message;
try {
HttpHeaders httpHeaders = Common.createAuthenticationHeaders("stephane" + ":" + "mypassword");
ResponseEntity<GreetingResource> responseEntity = restTemplate.getForEntity("/admin/greeting", GreetingResource.class, httpHeaders);
GreetingResource greetingResource = responseEntity.getBody();
message = greetingResource.getMessage();
} catch (HttpMessageNotReadableException e) {
message = "The GET request FAILED with the message being not readable: " + e.getMessage();
} catch (HttpStatusCodeException e) {
message = "The GET request FAILED with the HttpStatusCode: " + e.getStatusCode() + "|" + e.getStatusText();
} catch (RuntimeException e) {
message = "The GET request FAILED " + ExceptionUtils.getFullStackTrace(e);
}
return message;
}
The http headers are created by a utility:
static public HttpHeaders createAuthenticationHeaders(String usernamePassword) {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
byte[] encodedAuthorisation = Base64.encode(usernamePassword.getBytes());
headers.add("Authorization", "Basic " + new String(encodedAuthorisation));
return headers;
}
The web security configuration and code work fine. I make sure of this using a mockMvc based integration test which succeeds.
The only test that fails is the one based on the REST template:
#Test
public void testGreeting() throws Exception {
mockServer.expect(requestTo("/admin/greeting")).andExpect(method(HttpMethod.GET)).andRespond(withStatus(HttpStatus.OK));
String message = adminRestClient.getGreetingMessage();
mockServer.verify();
assertThat(message, allOf(containsString("Hello"), containsString("World")));
}
The exception given in the Maven build console output is:
java.lang.AssertionError:
Expected: (a string containing "Hello" and a string containing "World")
got: "The GET request FAILED org.springframework.web.client.RestClientException : Could not extract response: no suitable HttpMessageConverter found for response type [class com.thalasoft.learnintouch.rest.resource.GreetingR esource] and content type [application/octet-stream]\n\tat org.springframework.web.client.HttpMessageConverte rExtractor.extractData(HttpMessageConverterExtract or.java:107)
I'm using the Spring Framework 3.2.2.RELEASE version and the Spring Security 3.1.4.RELEASE version on the Java 1.6 version.
At first, I had a bare bone REST template:
#Bean
public RestTemplate restTemplate() {
RestTemplate restTemplate = new RestTemplate();
return restTemplate;
}
I have now added to it, hoping it would help:
private static final Charset UTF8 = Charset.forName("UTF-8");
#Bean
public RestTemplate restTemplate() {
List<HttpMessageConverter<?>> messageConverters = new ArrayList<HttpMessageConverter<?>>();
MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter = new MappingJackson2HttpMessageConverter();
mappingJackson2HttpMessageConverter.setSupportedMediaTypes(Arrays.asList(new MediaType("application", "json", UTF8)));
messageConverters.add(mappingJackson2HttpMessageConverter);
Jaxb2Marshaller jaxb2Marshaller = new Jaxb2Marshaller();
jaxb2Marshaller.setClassesToBeBound(new Class[] {
GreetingResource.class
});
MarshallingHttpMessageConverter marshallingHttpMessageConverter = new MarshallingHttpMessageConverter(jaxb2Marshaller, jaxb2Marshaller);
messageConverters.add(marshallingHttpMessageConverter);
messageConverters.add(new ByteArrayHttpMessageConverter());
messageConverters.add(new FormHttpMessageConverter());
StringHttpMessageConverter stringHttpMessageConverter = new StringHttpMessageConverter();
stringHttpMessageConverter.setSupportedMediaTypes(Arrays.asList(new MediaType("text", "plain", UTF8)));
messageConverters.add(stringHttpMessageConverter);
messageConverters.add(new BufferedImageHttpMessageConverter());
messageConverters.add(new Jaxb2RootElementHttpMessageConverter());
messageConverters.add(new AllEncompassingFormHttpMessageConverter());
RestTemplate restTemplate = new RestTemplate();
restTemplate.setMessageConverters(messageConverters);
return restTemplate;
}
But it didn't change anything and the exception remains the same.
My understanding is that, it is not the REST template that needs any specific JSON configuration, but rather, that, for some reason, my controller is spitting out some application/octet-stream content type instead of some application/json content type.
Any clue?
Some additional information...
The admin rest client bean in the web test configuration:
#Configuration
public class WebTestConfiguration {
#Bean
public AdminRestClient adminRestClient() {
return new AdminRestClient();
}
#Bean
public RestTemplate restTemplate() {
List<HttpMessageConverter<?>> messageConverters = new ArrayList<HttpMessageConverter<?>>();
MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter = new MappingJackson2HttpMessageConverter();
mappingJackson2HttpMessageConverter.setSupportedMediaTypes(Arrays.asList(new MediaType("application", "json", UTF8)));
messageConverters.add(mappingJackson2HttpMessageConverter);
Jaxb2Marshaller jaxb2Marshaller = new Jaxb2Marshaller();
jaxb2Marshaller.setClassesToBeBound(new Class[] {
Greeting.class
});
MarshallingHttpMessageConverter marshallingHttpMessageConverter = new MarshallingHttpMessageConverter(jaxb2Marshaller, jaxb2Marshaller);
messageConverters.add(marshallingHttpMessageConverter);
messageConverters.add(new ByteArrayHttpMessageConverter());
messageConverters.add(new FormHttpMessageConverter());
StringHttpMessageConverter stringHttpMessageConverter = new StringHttpMessageConverter();
stringHttpMessageConverter.setSupportedMediaTypes(Arrays.asList(new MediaType("text", "plain", UTF8)));
messageConverters.add(stringHttpMessageConverter);
messageConverters.add(new BufferedImageHttpMessageConverter());
messageConverters.add(new Jaxb2RootElementHttpMessageConverter());
messageConverters.add(new AllEncompassingFormHttpMessageConverter());
RestTemplate restTemplate = new RestTemplate();
restTemplate.setMessageConverters(messageConverters);
return restTemplate;
}
}
The base test class:
#RunWith(SpringJUnit4ClassRunner.class)
#WebAppConfiguration
#ContextConfiguration( classes = { ApplicationConfiguration.class, WebSecurityConfig.class, WebConfiguration.class, WebTestConfiguration.class })
#Transactional
public abstract class AbstractControllerTest {
#Autowired
private WebApplicationContext webApplicationContext;
#Autowired
private FilterChainProxy springSecurityFilterChain;
#Autowired
protected RestTemplate restTemplate;
protected MockRestServiceServer mockServer;
#Before
public void setup() {
this.mockServer = MockRestServiceServer.createServer(restTemplate);
}
}
The web init class:
public class WebInit implements WebApplicationInitializer {
private static Logger logger = LoggerFactory.getLogger(WebInit.class);
#Override
public void onStartup(ServletContext servletContext) throws ServletException {
registerListener(servletContext);
registerDispatcherServlet(servletContext);
registerJspServlet(servletContext);
createSecurityFilter(servletContext);
}
private void registerListener(ServletContext servletContext) {
// Create the root application context
AnnotationConfigWebApplicationContext appContext = createContext(ApplicationConfiguration.class, WebSecurityConfig.class);
// Set the application display name
appContext.setDisplayName("LearnInTouch");
// Create the Spring Container shared by all servlets and filters
servletContext.addListener(new ContextLoaderListener(appContext));
}
private void registerDispatcherServlet(ServletContext servletContext) {
AnnotationConfigWebApplicationContext webApplicationContext = createContext(WebConfiguration.class);
ServletRegistration.Dynamic dispatcher = servletContext.addServlet("dispatcher", new DispatcherServlet(webApplicationContext));
dispatcher.setLoadOnStartup(1);
Set<String> mappingConflicts = dispatcher.addMapping("/");
if (!mappingConflicts.isEmpty()) {
for (String mappingConflict : mappingConflicts) {
logger.error("Mapping conflict: " + mappingConflict);
}
throw new IllegalStateException(
"The servlet cannot be mapped to '/'");
}
}
private void registerJspServlet(ServletContext servletContext) {
}
private AnnotationConfigWebApplicationContext createContext(final Class... modules) {
AnnotationConfigWebApplicationContext appContext = new AnnotationConfigWebApplicationContext();
appContext.register(modules);
return appContext;
}
private void createSecurityFilter(ServletContext servletContext) {
FilterRegistration.Dynamic springSecurityFilterChain = servletContext.addFilter("springSecurityFilterChain", DelegatingFilterProxy.class);
springSecurityFilterChain.addMappingForUrlPatterns(null, false, "/*");
}
}
The web configuration:
#Configuration
#EnableWebMvc
#EnableEntityLinks
#ComponentScan(basePackages = "com.thalasoft.learnintouch.rest.controller")
public class WebConfiguration extends WebMvcConfigurerAdapter {
#Override
public void addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) {
PageableArgumentResolver resolver = new PageableArgumentResolver();
resolver.setFallbackPageable(new PageRequest(1, 10));
resolvers.add(new ServletWebArgumentResolverAdapter(resolver));
super.addArgumentResolvers(resolvers);
}
}
The application configuration is empty for now:
#Configuration
#Import({ ApplicationContext.class })
public class ApplicationConfiguration extends WebMvcConfigurerAdapter {
// Declare "application" scope beans here, that is, beans that are not only used by the web context
}
I had my doubts before, but now that you've posted everything, here's what's up. Assuming the RestTemplate object you use in your getGreetingMessage() method is the same as the one declared in the #Bean method, the problem starts here
this.mockServer = MockRestServiceServer.createServer(restTemplate);
This call overwrites the default ClientHttpRequestFactory object that the RestTemplate object uses internally with a mock. In your getGreetingMessage() method, this call
ResponseEntity<GreetingResource> responseEntity = restTemplate.getForEntity("/admin/greeting", GreetingResource.class, httpHeaders);
doesn't actually go through the network. The RestTemplate uses the mocked ClientHttpRequestFactory to create a fake ClientHttpRequest which produces a fake ClientHttpResponse which doesn't have a Content-Type header. When the RestTemplate looks at the ClientHttpResponse to determine its Content-Type and doesn't find one, it assumes application/octet-stream by default.
So, your controller isn't setting the content type because your controller is never hit. The RestTemplate is using a default content type for your response because it is mocked and doesn't actually contain one.
From your comments:
I wonder if I understand what the mock server is testing. I understand
it is to be used in acceptance testing scenario. Is it supposed to hit
the controller at all ?
The javadoc for MockRestServiceServer states:
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.
In other words, it's as if your application server didn't exist. So you could throw any expectations (and actual return values) you wanted and test whatever happens from the client side. So you aren't testing your server, you are testing your client.
Are you sure you aren't looking for MockMvc, which is
Main entry point for server-side Spring MVC test support.
which you can setup to actually use your #Controller beans in an integration environment. You aren't actually sending HTTP request, but the MockMvc is simulating how they would be sent and how your server would respond.
It is bug in MockHttpServletRequest and I will try to describe it.
Issue in tracker https://jira.springsource.org/browse/SPR-11308#comment-97327
Fixed in version 4.0.1
Bug
When DispatcherServlet looking for method to invoke it using some RequestConditions. One of them is ConsumesRequestCondition. The following is a piece of code:
#Override
protected boolean matchMediaType(HttpServletRequest request) throws HttpMediaTypeNotSupportedException {
try {
MediaType contentType = StringUtils.hasLength(request.getContentType()) ?
MediaType.parseMediaType(request.getContentType()) :
MediaType.APPLICATION_OCTET_STREAM;
return getMediaType().includes(contentType);
}
catch (IllegalArgumentException ex) {
throw new HttpMediaTypeNotSupportedException(
"Can't parse Content-Type [" + request.getContentType() + "]: " + ex.getMessage());
}
}
We are interested in piece request.getContentType(). There request is MockHttpServletRequest. Let's look on method getContentType():
public String getContentType() {
return this.contentType;
}
It just return value of this.contentType. It does not return a value from the header! And this.contentType is always NULL. Then contentType in matchMediaType methos will be always MediaType.APPLICATION_OCTET_STREAM.
Solution
I have tried many ways but have found only one that works.
Create package org.springframework.test.web.client in your test directory.
Create copy of org.springframework.test.web.client.MockMvcClientHttpRequestFactory but rename it. For example rename to FixedMockMvcClientHttpRequestFactory.
Find line:
MvcResult mvcResult = MockMvcClientHttpRequestFactory.this.mockMvc.perform(requestBuilder).andReturn();
Replace it with code:
MvcResult mvcResult = FixedMockMvcClientHttpRequestFactory.this.mockMvc.perform(new RequestBuilder() {
#Override
public MockHttpServletRequest buildRequest(ServletContext servletContext) {
MockHttpServletRequest request = requestBuilder.buildRequest(servletContext);
request.setContentType(request.getHeader("Content-Type"));
return request;
}
}).andReturn();
And register your ClientHttpReque
#Bean
public ClientHttpRequestFactory clientHttpRequestFactory(MockMvc mockMvc) {
return new FixedMockMvcClientHttpRequestFactory(mockMvc);
}
I know that it is not beautiful solution but it works fine.