Why Getting Empty Response when writing UnitTest - java

I am learning to write Unit Test for SpringBoot Restcontroller , wrote this and test passes
#RunWith(SpringRunner.class)
#SpringBootTest(classes = {FhirApp.class, TestSecurityConfiguration.class})
#AutoConfigureMockMvc
public class ObservationControllerTest {
private ObjectMapper objectMapper = new ObjectMapper();
#Autowired
private MockMvc mockMvc;
#MockBean
private ObservationService observationService;
#Test
public void createObservationResource() throws Exception {
given(observationService.createObservation(ResourceStringProvider.observationsource()))
.willReturn(responseDocument);
String jsonString = objectMapper.writeValueAsString(
ResourceStringProvider.observationsource());
mockMvc.perform(post("/Observation")
.contentType(MediaType.APPLICATION_JSON)
.content(jsonString))
.andExpect(status()
.isOk());
}
But as this and this , i am also getting empty response for response.getContentAsString() :
Mockito.when(observationService.createObservation(Mockito.any())).thenReturn(responseDocument);
String jsonString = objectMapper.writeValueAsString(ResourceStringProvider.observationsource());
MockHttpServletResponse response = mockMvc.perform(post("/Observation")
.contentType(MediaType.APPLICATION_JSON)
.content(jsonString))
.andReturn()
.getResponse();
assertThat(response.getContentAsString())
.isEqualTo(new ObjectMapper()
.writeValueAsString(responseDocument));
I already tried the solutions provided by them :
1: Using Mockito.any(String.class)
2: webEnvironment = SpringBootTest.WebEnvironment.MOCK
3: using thenCallRealMethod instead of thenReturn(responseDocument)
But unfortunately it didn't work,already tried different possibilities , I also tried using MockitoJunitRunner :
#RunWith(MockitoJUnitRunner.class)
#SpringBootTest(classes = {FhirApp.class, TestSecurityConfiguration.class})
#AutoConfigureMockMvc
public class ObservationControllerTest {
private MockMvc mockMvc;
#Mock
private ObservationService observationService;
#Mock
private RequestFilter requestFilter;
#InjectMocks
private ObservationController observationController;
#Before
public void setup() {
Resource resource = Utility.convertFromStringToFhirResource(Observation.class,ResourceStringProvider.observationResponse());
responseDocument=Utility.convertFromFhirResourceToMongoInsertibleDoc(resource);
//these line enabled for MockitoJUnitRunner only
this.mockMvc = MockMvcBuilders.standaloneSetup(observationController)
.setControllerAdvice(new FhirRuntimeException("Error Happened"))
.addFilters(requestFilter)
.build();
}
#Test
public void createObservationResource()throws Exception{
Mockito.when(observationService.createObservation(ResourceStringProvider.observationsource())).thenReturn(responseDocument);
String jsonString = objectMapper.writeValueAsString(ResourceStringProvider.observationsource());
MockHttpServletResponse response = mockMvc.perform(
post("/Observation")
.contentType(MediaType.APPLICATION_JSON)
.content(jsonString))
.andReturn()
.getResponse();
assertThat(response.getContentAsString()).isEqualTo(new ObjectMapper().writeValueAsString(responseDocument));
}
i think since not many have went through such issues, issue isn't much talked about . What could be the reason of empty response when response status is ok?
Controller code :
#RestController
#RequestMapping("/api")
public class ObservationController {
#Autowired
private ObservationService observationService;
#GetMapping("/Observation/{id}")
public ResponseEntity<Document> getObservationByID(
#RequestParam("_pretty") Optional<String> pretty,
#PathVariable("id") String id) {
Document resultDoc = observationService.getObservationById(id);
return new ResponseEntity<>(resultDoc, HttpStatus.OK);
}
#PostMapping(path = "/Observation", consumes = {"application/json", "application/fhir+json"},
produces = {"application/json", "application/fhir+json"})
public ResponseEntity<Document> createObservationResource(#RequestBody String fhirResource) {
Document fhirDoc = observationService.createObservation(fhirResource);
return new ResponseEntity<>(fhirDoc,
Utility.createHeaders(fhirDoc),
HttpStatus.CREATED);
}
//other methods
}
I realized the call to post in test should be /api/Observation , but it didn't make any difference . Thanks in Advance.

Posting the complete answer alongwith imports here so that it will help someone (actually we don't require any annotation above and it is one way to run it , during my findings i came accross this post which helps in solving design issue which may occur if you go ahead with #InjectMocks approach)
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import com.comitemd.emr.datalayer.fhir.service.ObservationService;
import com.comitemd.emr.datalayer.fhir.utility.ResourceStringProvider;
import com.comitemd.emr.datalayer.fhir.utility.Utility;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.bson.Document;
import org.hl7.fhir.r4.model.Observation;
import org.hl7.fhir.r4.model.Resource;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.result.MockMvcResultHandlers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
//#RunWith(MockitoJUnitRunner.class)
public class ObservationControllerStandaloneTest {
private MockMvc mockMvc;
#Mock
private ObservationService observationService;
#InjectMocks
private ObservationController observationController;
private Document responseDocument;
#Before
public void setup() {
MockitoAnnotations.initMocks(this);// enable this or MockitoJUnitRunner.class
Resource resource = Utility
.convertFromStringToFhirResource(Observation.class, ResourceStringProvider.observationResponse());
responseDocument=Utility.convertFromFhirResourceToMongoInsertibleDoc(resource);
this.mockMvc = MockMvcBuilders.standaloneSetup(observationController).build();
}
#Test
public void createObservationResource()throws Exception{
Mockito.when(observationService.createObservation(ResourceStringProvider.observationsource()))
.thenReturn(responseDocument);
MockHttpServletResponse response = mockMvc.perform(
post("/api/Observation")
.contentType(MediaType.APPLICATION_JSON)
.content(ResourceStringProvider.observationsource()))
.andDo(MockMvcResultHandlers.print())
.andReturn()
.getResponse();
verify(observationService, times(1)).createObservation(Mockito.any());
assertThat(response.getContentAsString()).isEqualTo(new ObjectMapper().writeValueAsString(responseDocument));
}
}

Related

Spring #Autowired restTemplate is null [duplicate]

This question already has answers here:
Why is my Spring #Autowired field null?
(21 answers)
Closed 4 years ago.
I am new to Spring. I develop Service that Consuming RESTful service with certficate using Java
Here is my Config class:
package configuration;
import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContextBuilder;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.util.ResourceUtils;
import org.springframework.web.client.RestTemplate;
import javax.net.ssl.SSLContext;
import java.util.function.Supplier;
#Configuration
public class RestClientCertConfig {
private char[] allPassword = "allpassword".toCharArray();
#Bean
public RestTemplate restTemplate(RestTemplateBuilder builder) throws Exception {
SSLContext sslContext = SSLContextBuilder
.create()
.loadKeyMaterial(ResourceUtils.getFile("classpath:keystore.jks"), allPassword, allPassword)
.loadTrustMaterial(ResourceUtils.getFile("classpath:truststore.jks"), allPassword)
.build();
HttpClient client = HttpClients.custom()
.setSSLContext(sslContext)
.build();
return builder
.requestFactory((Supplier<ClientHttpRequestFactory>)new HttpComponentsClientHttpRequestFactory(client))
.build();
}
}
And here is the class where I consume Restful EndPoint:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;
import java.net.URISyntaxException;
import java.util.Collections;
public class ECSConfigGet {
private static final String ECS_API_URI = "<RestEndPointToConsume";
#Autowired
private static RestTemplate restTemplate;
public static void main(String[] args) {
try {
makeECSCall("myTestHeaderValue");
} catch (URISyntaxException e) {
e.printStackTrace();
}
}
private static void makeECSCall(String entityCode) throws RestClientException, URISyntaxException {
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
headers.set("entityCode", entityCode);
HttpEntity<String> entity = new HttpEntity<>("parameters", headers);
ResponseEntity responseEntity = restTemplate.exchange(ECS_API_URI, HttpMethod.GET, entity, String.class);
}
}
Did I completely misunderstood the concept? I would expect restTemplate would not be null with all the Annotations I use. Thank for any help!
NullPointerException is fixed. ECSConfigGet looks like:
package main;
import configuration.RestClientCertConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;
import services.modelsdto.ExpenseConfigDTO;
import java.util.Collections;
#SpringBootApplication
#Component
public class ECSConfigGet implements CommandLineRunner{
//API to call
private static final String ECS_API_URI = "<API_TO_CONSUME>";
#Autowired
private RestTemplate restTemplate;
public static void main(String[] args) {
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(RestClientCertConfig.class);
applicationContext.getBean(RestTemplate.class);
SpringApplication.run(ECSConfigGet.class, args);
}
private void makeECSCall(String entityCode) throws RestClientException {
ExpenseConfigDTO expenseConfigDTO = new ExpenseConfigDTO();
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
headers.set("entityCode", entityCode);
HttpEntity<String> entity = new HttpEntity<>("parameters", headers);
ResponseEntity responseEntity = restTemplate.exchange(ECS_API_URI, HttpMethod.GET, entity, String.class);
}
#Override
public void run(String... args) {
for (int i = 0; i < args.length; ++i) {
makeECSCall("myTestHeaderValue");
}
}
}
You're missing a bit of Spring boilerplate that you need to make #Autowired work. If you're using Spring Boot, you're close, but #Patrick is right generally: ECSConfigGet needs to be a bean by annotating it correctly, but you also need to run your application within an application context in order for any of the Spring magic to happen. I suggest checking out this tutorial on how to use Spring Boot in a command line application.
The high level is ECSConfigGet needs to be annotated with #SpringBootApplication and then have it implement CommandLineRunner and then from the run method, you will have access to the #Autowired component. Spring will instantiate ECSConfigGet and populate the properties. Also as #Roddy pointed out, RestTemplate cannot be static, either.
The ECSConfigGet class is not a bean so it can not autowire a component.
Add #Component as class annotation to ECSConfigGet

Spring WebTestClient JSON LocalDate decode

When using WebTestClient in Spring Boot 2.0.1 I get different formatted dates depending on how I bind the test client see code below.
So how can I get the WebTestClient.bindToController to return LocalDate formatted as 2018-04-13? When I call WebTestClient.bindToServer() I get expected format.
#RestController
public class TodayController {
#GetMapping("/today")
public Map<String, Object> fetchToday() {
return ImmutableMap.of("today", LocalDate.now());
}
}
Tests:
#ExtendWith({SpringExtension.class})
#SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class TodayControllerTest {
#LocalServerPort
private int randomPort;
#Autowired
private TodayController controller;
#Test
void fetchTodayWebTestClientBoundToController() {
WebTestClient webTestClient = WebTestClient.bindToController(controller)
.configureClient()
.build();
webTestClient.get().uri("/today")
.exchange()
.expectBody()
.json("{\"today\":[2018,4,13]}");
}
#Test
void fetchTodayWebTestClientBoundToServer() {
WebTestClient webTestClient = WebTestClient.bindToServer()
.baseUrl("http://localhost:" + randomPort)
.build();
webTestClient.get().uri("/today")
.exchange()
.expectBody()
.json("{\"today\":\"2018-04-13\"}");
}
As it turns out I need to set the Jackson decoder/encoder when using WebTestClient.bindToController. e.g.
#Test
public void fetchTodayWebTestClientBoundToController() {
WebTestClient webTestClient = WebTestClient.bindToController(controller)
.httpMessageCodecs((configurer) -> {
CodecConfigurer.DefaultCodecs defaults = configurer.defaultCodecs();
defaults.jackson2JsonDecoder(new Jackson2JsonDecoder(objectMapper, new MimeType[0]));
defaults.jackson2JsonEncoder(new Jackson2JsonEncoder(objectMapper, new MimeType[0]));
})
.configureClient()
.build();
webTestClient.get().uri("/today")
.exchange()
.expectBody()
.json("{\"today\":\"2018-04-30\"}");
}
More detailed answer from Spring boot project
Add this file with configuration
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.http.codec.ServerCodecConfigurer;
import org.springframework.http.codec.json.Jackson2JsonDecoder;
import org.springframework.http.codec.json.Jackson2JsonEncoder;
import org.springframework.web.reactive.config.WebFluxConfigurer;
#Configuration
#Import(JacksonAutoConfiguration.class)
#AutoConfigureAfter(JacksonAutoConfiguration.class)
public class JacksonTestConfiguration {
#Bean
WebFluxConfigurer webFluxConfigurer(ObjectMapper objectMapper) {
return new WebFluxConfigurer() {
#Override
public void configureHttpMessageCodecs(ServerCodecConfigurer configurer) {
configurer.defaultCodecs().jackson2JsonEncoder(new Jackson2JsonEncoder(objectMapper));
configurer.defaultCodecs().jackson2JsonDecoder(new Jackson2JsonDecoder(objectMapper));
}
};
}
}

Access springbeans in JerseyTest with Jersey2.0

I have jersey project with spring. Now My test is deriverd from JerseyTest. When I try to do
#AutoWired
RestTemplate restTemplate;
It looks like spring is not working in jersey test. I did some research and found some links like
spring_jersey
but it did not work ,since I am using jersey2.0.
My code looks like
//AbstractTest
package com.test;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.Application;
import org.glassfish.jersey.client.ClientConfig;
import org.glassfish.jersey.filter.LoggingFilter;
import org.glassfish.jersey.jackson.JacksonFeature;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.test.JerseyTest;
import org.glassfish.jersey.server.ServerProperties;
import org.glassfish.jersey.server.validation.ValidationFeature;
public abstract class AbstractTest extends JerseyTest
{
protected WebTarget getRootTarget(final String rootResource)
{
return client().target(getBaseUri()).path(rootResource);
}
#Override
protected final Application configure()
{
final ResourceConfig application = configureApplication();
// needed for json serialization
application.register(JacksonFeature.class);
// bean validation
application.register(ValidationFeature.class);
// configure spring context
application.property("contextConfigLocation", "classpath:/META-INF/applicationContext.xml");
// disable bean validation for tests
application.property(ServerProperties.BV_FEATURE_DISABLE, "true");
return application;
}
protected abstract ResourceConfig configureApplication();
#Override
protected void configureClient(final ClientConfig config)
{
// needed for json serialization
config.register(JacksonFeature.class);
config.register(new LoggingFilter(java.util.logging.Logger.getLogger(AbstractResourceTest.class.getName()), false));
super.configureClient(config);
}
}
package com.test;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.content;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.method;
import static org.springframework.test.web.client.response.MockRestResponseCreators.withSuccess;
//MyTest
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.Response;
import org.apache.commons.io.IOUtils;
import org.glassfish.jersey.server.ResourceConfig;
import org.junit.Before;
import org.junit.Test;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.test.web.client.MockRestServiceServer;
import org.springframework.test.web.client.match.MockRestRequestMatchers;
import org.springframework.web.client.RestTemplate;
import junit.framework.Assert;
public final class MyTest extends AbstractTest
{
private static final String ROOT_RESOURCE_PATH = "/testUrl";
#AutoWired
private RestTemplate restTemplate;
private MockRestServiceServer mockServer;
#Before
public void setup(){
this.restTemplate = new RestTemplate();
this.mockServer = MockRestServiceServer.createServer(restTemplate);
}
#Test
public void testPostWithString() {
WebTarget target = getRootTarget(ROOT_RESOURCE_PATH).path("");
String entityBody = new String();
entityBody = " My test data";
final javax.ws.rs.client.Entity<String> entity = javax.ws.rs.client.Entity.entity(entityBody, "text/plain");
mockServer.expect(MockRestRequestMatchers.requestTo(ROOT_RESOURCE_PATH)).andExpect(method(HttpMethod.POST)).andExpect(content().string(entityBody))
.andRespond(withSuccess("resultSuccess", MediaType.TEXT_PLAIN));
final Response response = target.request().post(entity);
Assert.assertNotNull("Response must not be null", response.getEntity());
Assert.assertEquals("Response does not have expected response code", 200, response.getStatus());
System.out.println("Response = " + response.getEntity());
String data = response.readEntity(String.class);
System.out.println("Response = " + data);
if(response.ok() != null)
{
System.out.println("Ok");
}
}
}
Update:
public class SimpleJerseyTest extends ApplicationContextAwareJerseyTest {
private static final String ROOT_RESOURCE_PATH = "/test";
#Override
public void configureApplication(ResourceConfig config) {
config.register(MyApp.class);
config.register(new LoggingFilter(Logger.getAnonymousLogger(), true));
}
#Before
public void setUp() {
try{
((ConfigurableApplicationContext)this.applicationContext).refresh();
super.setUp();
}catch(Exception e){
}
this.mockServer = MockRestServiceServer.createServer(restTemplate);
}
#Autowired
private RestTemplate restTemplate;
private MockRestServiceServer mockServer;
#Test
public void doitOnce() {
WebTarget target = target(ROOT_RESOURCE_PATH);
String entityBody = new String();
final javax.ws.rs.client.Entity<String> entity = javax.ws.rs.client.Entity.entity(entityBody, "text/plain");
mockServer.expect(MockRestRequestMatchers.requestTo(ROOT_RESOURCE_PATH)).andExpect(method(HttpMethod.POST)).andExpect(content().string(entityBody))
.andRespond(withSuccess("resultSuccess", MediaType.TEXT_PLAIN));
final Response response = target.request().post(entity);
System.out.println("Response = " + response.getEntity());
String data = response.readEntity(String.class);
System.out.println("Response = " + data);
if(response.ok() != null)
{
System.out.println("Ok");
}
}
}
I have added bean in
src/test/resources/META-INF/applicationContext.xml
<!-- Our REST Web Service client -->
<bean id="restTemplate" class="org.springframework.web.client.RestTemplate"/>
Same bean I have added in
src/main/resources/META-INF/applicationContext.xml
!-- Our REST Web Service client -->
<bean id="restTemplate" class="org.springframework.web.client.RestTemplate"/>
Instead of configuring Spring like this
application.property("contextConfigLocation", "classpath:/META-INF/applicationContext.xml");
You can instead use
application.property("contextConfig", <ApplicationContext>);
This way you can have an instance of the ApplicationContext, where you can get the AutowireCapableBeanFactory. With this, you can just call acbf.autowireBean(this) to inject the test class.
Here's what I mean. I tested it, and it works find for simple cases. Won't work well though if the beans you are trying to inject aren't singletons, as new one will be create for the test and where ever else you try to inject to in your application code
public abstract class ApplicationContextAwareJerseyTest extends JerseyTest {
protected ApplicationContext applicationContext;
#Override
protected final ResourceConfig configure() {
final ResourceConfig config = new ResourceConfig();
configureApplication(config);
this.applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
config.property("contextConfig", this.applicationContext);
final AutowireCapableBeanFactory bf = this.applicationContext.getAutowireCapableBeanFactory();
bf.autowireBean(this);
return config;
}
public final ApplicationContext getApplicationContext() {
return this.applicationContext;
}
protected void configureApplication(ResourceConfig resourceConfig) {};
}
One thing I am not sure about though is how the resetting would work. I tried to add
#Before
public void setUp() throws Exception {
((ConfigurableApplicationContext)this.applicationContext).refresh();
super.setUp();
}
into the abstract class, but that doesn't seem to work as expected. The test I used is as follows
public class SimpleJerseyTest extends ApplicationContextAwareJerseyTest {
#Path("test")
public static class SimpleResource {
#Autowired
private MessageService service;
#GET
public String getMessage() {
return this.service.getMessage();
}
}
#Override
public void configureApplication(ResourceConfig config) {
config.register(SimpleResource.class);
config.register(new LoggingFilter(Logger.getAnonymousLogger(), true));
}
#Before
public void before() {
assertEquals("Hello World", messageService.getMessage());
}
#Autowired
private MessageService messageService;
#Test
public void doitOnce() {
messageService.setMessage("BOOYAH");
final Response response = target("test").request().get();
assertEquals("BOOYAH", response.readEntity(String.class));
}
#Test
public void doitTwice() {
messageService.setMessage("BOOYAH");
final Response response = target("test").request().get();
assertEquals("BOOYAH", response.readEntity(String.class));
}
}
The result I would get for the second test is that the value of the service message was the default message "Hello World", even though I set the message to "BOOYAH". This tells me that there is a stale service in the application, which is not the same one being injected into the test. The first test works fine though. Without resetting, the second test would work fine also, but you are left with modified services in each test, which makes the test not self-contained.

Can't upload multipart file with mockMvc [duplicate]

I have the following request handler for saving autos. I have verified that this works when I use e.g. cURL. Now I want to unit test the method with Spring MVC Test. I have tried to use the fileUploader, but I am not managing to get it working. Nor do I manage to add the JSON part.
How would I unit test this method with Spring MVC Test? I am not able to find any examples on this.
#RequestMapping(value = "autos", method = RequestMethod.POST)
public ResponseEntity saveAuto(
#RequestPart(value = "data") autoResource,
#RequestParam(value = "files[]", required = false) List<MultipartFile> files) {
// ...
}
I want to uplod a JSON representation for my auto + one or more files.
I will add 100 in bounty to the correct answer!
Since MockMvcRequestBuilders#fileUpload is deprecated, you'll want to use MockMvcRequestBuilders#multipart(String, Object...) which returns a MockMultipartHttpServletRequestBuilder. Then chain a bunch of file(MockMultipartFile) calls.
Here's a working example. Given a #Controller
#Controller
public class NewController {
#RequestMapping(value = "/upload", method = RequestMethod.POST)
#ResponseBody
public String saveAuto(
#RequestPart(value = "json") JsonPojo pojo,
#RequestParam(value = "some-random") String random,
#RequestParam(value = "data", required = false) List<MultipartFile> files) {
System.out.println(random);
System.out.println(pojo.getJson());
for (MultipartFile file : files) {
System.out.println(file.getOriginalFilename());
}
return "success";
}
static class JsonPojo {
private String json;
public String getJson() {
return json;
}
public void setJson(String json) {
this.json = json;
}
}
}
and a unit test
#WebAppConfiguration
#ContextConfiguration(classes = WebConfig.class)
#RunWith(SpringJUnit4ClassRunner.class)
public class Example {
#Autowired
private WebApplicationContext webApplicationContext;
#Test
public void test() throws Exception {
MockMultipartFile firstFile = new MockMultipartFile("data", "filename.txt", "text/plain", "some xml".getBytes());
MockMultipartFile secondFile = new MockMultipartFile("data", "other-file-name.data", "text/plain", "some other type".getBytes());
MockMultipartFile jsonFile = new MockMultipartFile("json", "", "application/json", "{\"json\": \"someValue\"}".getBytes());
MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
mockMvc.perform(MockMvcRequestBuilders.multipart("/upload")
.file(firstFile)
.file(secondFile)
.file(jsonFile)
.param("some-random", "4"))
.andExpect(status().is(200))
.andExpect(content().string("success"));
}
}
And the #Configuration class
#Configuration
#ComponentScan({ "test.controllers" })
#EnableWebMvc
public class WebConfig extends WebMvcConfigurationSupport {
#Bean
public MultipartResolver multipartResolver() {
CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
return multipartResolver;
}
}
The test should pass and give you output of
4 // from param
someValue // from json file
filename.txt // from first file
other-file-name.data // from second file
The thing to note is that you are sending the JSON just like any other multipart file, except with a different content type.
The method MockMvcRequestBuilders.fileUpload is deprecated use MockMvcRequestBuilders.multipart instead.
This is an example:
import static org.hamcrest.CoreMatchers.containsString;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.ResultActions;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultHandlers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.multipart.MultipartFile;
/**
* Unit test New Controller.
*
*/
#RunWith(SpringRunner.class)
#WebMvcTest(NewController.class)
public class NewControllerTest {
private MockMvc mockMvc;
#Autowired
WebApplicationContext wContext;
#MockBean
private NewController newController;
#Before
public void setup() {
this.mockMvc = MockMvcBuilders.webAppContextSetup(wContext)
.alwaysDo(MockMvcResultHandlers.print())
.build();
}
#Test
public void test() throws Exception {
// Mock Request
MockMultipartFile jsonFile = new MockMultipartFile("test.json", "", "application/json", "{\"key1\": \"value1\"}".getBytes());
// Mock Response
NewControllerResponseDto response = new NewControllerDto();
Mockito.when(newController.postV1(Mockito.any(Integer.class), Mockito.any(MultipartFile.class))).thenReturn(response);
mockMvc.perform(MockMvcRequestBuilders.multipart("/fileUpload")
.file("file", jsonFile.getBytes())
.characterEncoding("UTF-8"))
.andExpect(status().isOk());
}
}
Have a look at this example taken from the spring MVC showcase, this is the link to the source code:
#RunWith(SpringJUnit4ClassRunner.class)
public class FileUploadControllerTests extends AbstractContextControllerTests {
#Test
public void readString() throws Exception {
MockMultipartFile file = new MockMultipartFile("file", "orig", null, "bar".getBytes());
webAppContextSetup(this.wac).build()
.perform(fileUpload("/fileupload").file(file))
.andExpect(model().attribute("message", "File 'orig' uploaded successfully"));
}
}
Here's what worked for me, here I'm attaching a file to my EmailController under test. Also take a look at the postman screenshot on how I'm posting the data.
#WebAppConfiguration
#RunWith(SpringRunner.class)
#SpringBootTest(
classes = EmailControllerBootApplication.class
)
public class SendEmailTest {
#Autowired
private WebApplicationContext webApplicationContext;
#Test
public void testSend() throws Exception{
String jsonStr = "{\"to\": [\"email.address#domain.com\"],\"subject\": "
+ "\"CDM - Spring Boot email service with attachment\","
+ "\"body\": \"Email body will contain test results, with screenshot\"}";
Resource fileResource = new ClassPathResource(
"screen-shots/HomePage-attachment.png");
assertNotNull(fileResource);
MockMultipartFile firstFile = new MockMultipartFile(
"attachments",fileResource.getFilename(),
MediaType.MULTIPART_FORM_DATA_VALUE,
fileResource.getInputStream());
assertNotNull(firstFile);
MockMvc mockMvc = MockMvcBuilders.
webAppContextSetup(webApplicationContext).build();
mockMvc.perform(MockMvcRequestBuilders
.multipart("/api/v1/email/send")
.file(firstFile)
.param("data", jsonStr))
.andExpect(status().is(200));
}
}
If you are using Spring4/SpringBoot 1.x, then it's worth mentioning that you can add "text" (json) parts as well . This can be done via MockMvcRequestBuilders.fileUpload().file(MockMultipartFile file) (which is needed as method .multipart() is not available in this version):
#Test
public void test() throws Exception {
mockMvc.perform(
MockMvcRequestBuilders.fileUpload("/files")
// file-part
.file(makeMultipartFile( "file-part" "some/path/to/file.bin", "application/octet-stream"))
// text part
.file(makeMultipartTextPart("json-part", "{ \"foo\" : \"bar\" }", "application/json"))
.andExpect(status().isOk())));
}
private MockMultipartFile(String requestPartName, String filename,
String contentType, String pathOnClassPath) {
return new MockMultipartFile(requestPartName, filename,
contentType, readResourceFile(pathOnClasspath);
}
// make text-part using MockMultipartFile
private MockMultipartFile makeMultipartTextPart(String requestPartName,
String value, String contentType) throws Exception {
return new MockMultipartFile(requestPartName, "", contentType,
value.getBytes(Charset.forName("UTF-8")));
}
private byte[] readResourceFile(String pathOnClassPath) throws Exception {
return Files.readAllBytes(Paths.get(Thread.currentThread().getContextClassLoader()
.getResource(pathOnClassPath).toUri()));
}
}

unit test Spring MissingServletRequestParameterException JSON response

I have POST method in a Spring boot rest controller as follows
#RequestMapping(value="/post/action/bookmark", method=RequestMethod.POST)
public #ResponseBody Map<String, String> bookmarkPost(
#RequestParam(value="actionType",required=true) String actionType,
#RequestParam(value="postId",required=true) String postId,
#CurrentUser User user) throws Exception{
return service.bookmarkPost(postId, actionType, user);
}
now if I test with missing parameter in Postman I get an 400 http response and a JSON body:
{
"timestamp": "2015-07-20",
"status": 400,
"error": "Bad Request",
"exception": "org.springframework.web.bind.MissingServletRequestParameterException",
"message": "Required String parameter 'actionType' is not present",
"path": "/post/action/bookmark"
}
until now it's OK, but when I try to unit test I don't get the JSON response back
#Test
public void bookmarkMissingActionTypeParam() throws Exception{
// #formatter:off
mockMvc.perform(
post("/post/action/bookmark")
.accept(MediaType.APPLICATION_JSON)
.param("postId", "55ab8831036437e96e8250b6")
)
.andExpect(status().isBadRequest())
.andExpect(jsonPath("$.exception", containsString("MissingServletRequestParameterException")));
// #formatter:on
}
the test fails and produces
java.lang.IllegalArgumentException: json can not be null or empty
I did a .andDo(print()) and found that there is no body in the response
MockHttpServletResponse:
Status = 400
Error message = Required String parameter 'actionType' is not present
Headers = {X-Content-Type-Options=[nosniff], X-XSS-Protection=[1; mode=block], Cache-Control=[no-cache, no-store], Pragma=[no-cache], Expires=[1], X-Frame-Options=[DENY]}
Content type = null
Body =
Forwarded URL = null
Redirected URL = null
Cookies = []
why am I not getting the JSON response while unit testing my controller, but do receive it in manual testing using Postman or cUrl?
EDIT: I've added #WebIntegrationTest but got the same error:
import static org.hamcrest.Matchers.containsString;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.boot.test.WebIntegrationTest;
import org.springframework.http.MediaType;
import org.springframework.security.web.FilterChainProxy;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
#RunWith(SpringJUnit4ClassRunner.class)
#SpringApplicationConfiguration(classes = RestApplication.class)
#WebIntegrationTest
public class PostControllerTest {
private MockMvc mockMvc;
#Autowired
private WebApplicationContext webApplicationContext;
#Autowired
private FilterChainProxy springSecurityFilterChain;
#Before
public void setUp() {
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext)
.addFilter(springSecurityFilterChain)
.build();
}
#Test
public void bookmarkMissingActionTypeParam() throws Exception{
// #formatter:off
mockMvc.perform(
post("/post/action/bookmark")
.accept(MediaType.APPLICATION_JSON)
.param("postId", "55ab8831036437e96e8250b6")
)
.andDo(print())
.andExpect(status().isBadRequest())
.andExpect(jsonPath("$.exception", containsString("MissingServletRequestParameterException")));
// #formatter:on
}
}
This is because Spring Boot has auto-configured an exception handler org.springframework.boot.autoconfigure.web.BasicErrorController which is probably not present in your unit tests. A way to get it will be to use the Spring Boot testing support related annotations:
#SpringApplicationConfiguration
#WebIntegrationTest
More details are here
Update:
You are absolutely right, the behavior is very different in UI vs in test, the error pages which respond to status codes are not correctly hooked up in a non-servlet test environment. Improving this behavior can be a good bug to open for Spring MVC and/or Spring Boot.
For now, I have a workaround which simulates the behavior of BasicErrorController the following way:
#RunWith(SpringJUnit4ClassRunner.class)
#SpringApplicationConfiguration(classes = {RestApplication.class, TestConfiguration.class})
#WebIntegrationTest
public class PostControllerTest {
private MockMvc mockMvc;
#Autowired
private WebApplicationContext webApplicationContext;
#Autowired
private FilterChainProxy springSecurityFilterChain;
#Before
public void setUp() {
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext)
.addFilter(springSecurityFilterChain)
.build();
}
#Test
public void bookmarkMissingActionTypeParam() throws Exception{
// #formatter:off
mockMvc.perform(
post("/post/action/bookmark")
.accept(MediaType.APPLICATION_JSON)
.param("postId", "55ab8831036437e96e8250b6")
)
.andDo(print())
.andExpect(status().isBadRequest())
.andExpect(jsonPath("$.exception", containsString("MissingServletRequestParameterException")));
// #formatter:on
}
}
#Configuration
public static class TestConfiguration {
#Bean
public ErrorController errorController(ErrorAttributes errorAttributes) {
return new ErrorController(errorAttributes);
}
}
#ControllerAdvice
class ErrorController extends BasicErrorController {
public ErrorController(ErrorAttributes errorAttributes) {
super(errorAttributes);
}
#Override
#ExceptionHandler(Exception.class)
#ResponseBody
public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
return super.error(request);
}
}
What I am doing here is adding a ControllerAdvice which handles the Exception flow and delegates back to the BasicErrorController. This would atleast make the behavior consistent for you.
Originally, it should fix the error by #ResponseBody tag when defining your REST controller method. it will fix json error in the test class.
But, as you are using spring boot, you will define the controller class with #RestController and it should automatically take care of the error without defining #Controller and #ResponseType tags.

Categories