Null Body in SpringBoot WebMvcTest - junit

I am getting a result from my unit test that I don't quite understand.
Controller Code
package com.rk.capstone.controllers;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.rk.capstone.model.domain.User;
import com.rk.capstone.model.services.user.IUserService;
/**
* REST Controller for /register endpoint
*/
#RestController
#RequestMapping("/register")
public class RegisterController {
private final IUserService userService;
public RegisterController(IUserService userService) {
this.userService = userService;
}
#RequestMapping(value = "/user", method = RequestMethod.POST)
public ResponseEntity<User> registerNewUser(#RequestBody User user) {
if (userService.findByUserName(user.getUserName()) == null) {
user = userService.saveUser(user);
return ResponseEntity.status(HttpStatus.CREATED).body(user);
} else {
return ResponseEntity.status(HttpStatus.CONFLICT).body(null);
}
}
}
Unit Test Code:
package com.rk.capstone.controllers;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
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.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.rk.capstone.model.dao.UserDao;
import com.rk.capstone.model.domain.User;
import com.rk.capstone.model.services.user.IUserService;
import static org.mockito.BDDMockito.given;
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.status;
/**
* Class Provides Unit Testing for RegisterController
*/
#RunWith(SpringRunner.class)
#WebMvcTest(RegisterController.class)
public class RegisterControllerTest {
#MockBean
private IUserService userService;
#Autowired
private MockMvc mockMvc;
private User user;
private String userJson;
#Before
public void setup() {
user = new User("rick", "k", "rick#email.com", "rkow", "abc123");
ObjectMapper objectMapper = new ObjectMapper();
try {
userJson = objectMapper.writeValueAsString(user);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
}
#Test
public void testRegisterNewUserPostResponse() throws Exception {
given(this.userService.findByUserName(user.getUserName())).willReturn(null);
given(this.userService.saveUser(user)).willReturn(user);
Assert.assertNotNull("Mocked UserService is Null", this.userService);
this.mockMvc.perform(post("/register/user").content(userJson).
contentType(MediaType.APPLICATION_JSON)).
andExpect(status().isCreated()).
andDo(print()).andReturn();
}
}
The result of the print() is below, I do not understand why the Body is empty. I have tried numerous things I've read on other posts and blogs and no matter what I try the Body is always empty. Adding a Content-Type header in the controller response makes no difference.
MockHttpServletResponse:
Status = 201
Error message = null
Headers = {}
Content type = null
Body =
Forwarded URL = null
Redirected URL = null
Cookies = []
What is confounding me even more, is when I run the actual application and perform a POST using PostMan to the /register/user endpoint the response contains the body and status code I expect, a User represented via JSON, e.g.
Status Code: 201 Created
Response Body
{
"userId": 1,
"firstName": "rick",
"lastName": "k",
"emailAddress": "rick#email.com",
"userName": "rk",
"password": "abc123"
}
Any help or ideas is appreciated, using SpringBoot 1.4.0.RELEASE.
UPDATE: For some reason the following mocked method call is returning null in the controller under test.
given(this.userService.saveUser(user)).willReturn(user);

This thread ultimately turned me on to a solution:
Mockito when/then not returning expected value
Changed this line:
given(this.userService.saveUser(user)).willReturn(user);
to
given(this.userService.saveUser(any(User.class))).willReturn(user);

Related

Postman output "status":404,"error":"Not Found","path":"/api/employees"

the spring boot REST app with MySQL
I am trying to add record to DB and expect the record added and postman got it as output instead of the output "status":404,"error":"Not Found","path":"/api/employees" following is the classes
package com.controller;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.service.EmployeeService;
import com.model.Employee;
#RestController
#RequestMapping("/api")
public class EmployeeController {
private EmployeeService employeeservice;
public EmployeeController(EmployeeService employeeservice) {
super();
this.employeeservice = employeeservice;
}
//build create Employee REST API
#PostMapping("/employees")
public ResponseEntity<Employee> saveEmployee(#RequestBody Employee employee)
{
return new ResponseEntity<Employee>(employeeservice.saveEmployee(employee), HttpStatus.CREATED);
}
}
package com;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
#EnableJpaRepositories(
basePackages = {"com.model"})
#SpringBootApplication(scanBasePackages = {"service.impl"})
public class RestapimysqlApplication {
public static void main(String[] args) {
SpringApplication.run(RestapimysqlApplication.class, args);
}
}
It doesn't look like you're scanning the package that contains your REST controller (i.e. com.controller), seems like you're only scanning the service.impl package on your RestapimysqlApplication class.
You should probably add the com.controller to the list of packages being scanned by Spring here:
#EnableJpaRepositories(basePackages = {"com.repository"})
#SpringBootApplication(scanBasePackages = {"service.impl", "com"})
#EntityScan({"com.model"})
public class RestapimysqlApplication {
...
}

How to write Junit test case for vertx composit future or rxJava

Here is the method for which I need to write the Junit test case.
Problem is here to write JUnit test cases for the following method which return the future
public Future<SomeResponse> getSomeResponse(SomeQuery someQuery){
if(dbCircuitBreaker == null){
dbCircuitBreaker= CircuitBreakers.getDbCircuitBreaker();
}
return dbCircuitBreaker.execute(future -> {
List<SomeResponseMetaData> SomeResponseMetaDataList = new ArrayList<>();
SomeResponse someResponse = new SomeResponse();
Observable<Some> someMetaDataObservable = someSQLRepository.findSomeDetails(someQuery);
someMetaDataObservable.subscribe(some -> {
getSomeResponse(someResponseMetaDataList,some);
},throwable -> {
FIDAL_LOGGER.error(CLASS_FULL_NAME, "getSomeResponse", LogConstants.UNCAUGHT_ERROR, "Could not able to fetch the data from some", throwable);
},()->{
FIDAL_LOGGER.info(CLASS_FULL_NAME, "getSomeResponse", LogConstants.UNCAUGHT_ERROR, "fetch the data for some is completed");
someResponse.setSomeLists(someResponseMetaDataList);
future.complete(someResponse);
});
});
}
This the not the best solution but I have written which is working fine for me.
import io.vertx.rxjava.circuitbreaker.CircuitBreaker;
import io.vertx.rxjava.core.Future;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.modules.junit4.PowerMockRunner;
import rx.Single;
import rx.observers.TestSubscriber;
import java.util.ArrayList;
import java.util.List;
#RunWith(PowerMockRunner.class)
#PowerMockIgnore("javax.management.*")
public class FileServiceHelperTest {
#Mock
SomeServiceHelper someServiceHelper = null;
#InjectMocks
CircuitBreaker dbCircuitBreaker = null;
#InjectMocks
SomeLineSQLRepository someLineSQLRepository = null;
#Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
}
#Test
public void getSomeResponse() {
SomeResponseMetaData someResponseMetaData = new SomeResponseMetaData();
someResponseMetaData.setRecievedDate("2020-02-12T03:57:01-0600");
someResponseMetaData.setFileName("29579_3_Order_File1_20200207050043852");
someResponseMetaData.setSomeId("43b61ab4-52b8-48e6-9489-b5824d278254");
someResponseMetaData.setSomeStatus("PROCESSED");
someResponseMetaData.setSubmitted("3");
someResponseMetaData.setProcessed("0");
someResponseMetaData.setPending("0");
someResponseMetaData.setErrors("3");
someResponseMetaData.setSomeType("ORDER");
someResponseMetaData.setShipNodeId("29579_3");
List<SomeResponseMetaData> someResponseMetaDataList = new ArrayList();
someResponseMetaDataList.add(someResponseMetaData);
SomeResponse someResponseExpected = new SomeResponse();
someResponseExpected.setSomeLists(someResponseMetaDataList);
Future<SomeResponse> someResponseFuture = Future.succeededFuture(someResponseExpected);
SomeQuery someQuery = new SomeQuery.SomeQueryBuilder("29579").setPageNo(0).setPageSize(1).build();
Mockito.when(someServiceHelper.getSomeResponse(someQuery)).thenReturn(someResponseFuture);
Single<SomeResponse> someResponseSingle = someServiceHelper.getSomeResponse(someQuery).rxSetHandler();
TestSubscriber<SomeResponse> testSubscriber = new TestSubscriber();
someResponseSingle.subscribe(testSubscriber);
testSubscriber.assertCompleted();
testSubscriber.assertNoErrors();
testSubscriber.assertValue(someResponseExpected);
}
}

AEM Mockito unit testing issue

Since i am new to Mockito and AEM model java. I have a gone through some docs and wrote my first Mockito file for AEM Model java. In my code i've not see any errors, but while running i am not getting success and can't complete the code coverage 100%. Can anyone correct/help me to fix my code[given sample java with respective mockito file]
Java File:
import java.util.ArrayList;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.inject.Inject;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.resource.LoginException;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ValueMap;
import org.apache.sling.models.annotations.Model;
import org.apache.sling.models.annotations.injectorspecific.SlingObject;
import org.json.JSONException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.abc.cc.ddd.ResourceResolverService;
import com.abc.cc.ddd.services.models.bean.Accordion;
#Model(adaptables = SlingHttpServletRequest.class)
public class AccordionModel {
private final static Logger log = LoggerFactory.getLogger(AccordionModel.class);
#SlingObject
private SlingHttpServletRequest request;
#Inject
public ResourceResolverService resolverService;
private Resource resource;
public List < Accordion > accordionList = new ArrayList < Accordion > ();
#PostConstruct
protected void init() throws LoginException, JSONException {
log.info("AccordionModel init method Start");
resource = request.getResource();
final ValueMap configurationOptionProperties = resource.getValueMap();
log.debug("iconfigurationOptionProperties is " + configurationOptionProperties);
String count = configurationOptionProperties.get("count", String.class);
if (count != null) {
for (int i = 1; i <= Integer.valueOf(count); i++) {
Accordion accordion = new Accordion();
String title = configurationOptionProperties.get("title" + i, String.class);
String rte = configurationOptionProperties.get("rte" + i, String.class);
accordion.setTitle(title);
accordion.setRte(rte);
accordionList.add(accordion);
}
}
log.info("AccordionModel init method End");
}
public List < Accordion > getAccordionList() {
return accordionList;
}
}
Mockito code
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.List;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.resource.LoginException;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ValueMap;
import org.json.JSONException;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import com.abc.cc.ddd.ResourceResolverService;
import com.abc.cc.ddd.services.models.bean.Accordion;
#RunWith(MockitoJUnitRunner.class)
public class AccordionModelTest {
#InjectMocks
private AccordionModel accordionModel;
#Mock
Resource resource;
#Mock
SlingHttpServletRequest request;
#Mock
ResourceResolverService resourceResolverService;
#Mock
ValueMap valuemap;
public List < Accordion > accordionList = new ArrayList < Accordion > ();
String count = "6";
//max count, based on this count loop execute and get/set into the list
#Before
public void setUp() throws Exception {
when(request.getResource()).thenReturn(resource);
when(resource.getValueMap()).thenReturn(valuemap);
}
#Test
public void shouldReturnNullWhenPropertyIsNull() throws LoginException, JSONException {
when(valuemap.get("count", String.class)).thenReturn(null);
accordionModel.init();
assertEquals(accordionModel.getAccordionList(), null);
}
#Test
public void shouldReturnWhenPropertyNotNull() throws LoginException, JSONException {
when(valuemap.get("count", String.class)).thenReturn("count");
accordionModel.init();
assertEquals(accordionModel.getAccordionList(), count);
}
}
Errors in program its showing line--> accordionModel.init();
java.lang.NumberFormatException: For input string: "count"
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.valueOf(Unknown Source)
at com..services.sling.models.AccordionModel.init(AccordionModel.java:44) at
com..services.sling.models.AccordionModelTest.
shouldReturnWhenPropertyNotNull(AccordionModelTest.java:55)
java.lang.AssertionError: expected:<[]> but was:<null>
at org.junit.Assert.fail(Assert.java:88)
at org.junit.Assert.failNotEquals(Assert.java:834)
at org.junit.Assert.assertEquals(Assert.java:118)
at org.junit.Assert.assertEquals(Assert.java:144)
at com..services.sling.models.AccordionModelTest.
shouldReturnNullWhenPropertyIsNull(AccordionModelTest.java:53)
java.lang.AssertionError: expected:<[]> but was:<null>
If you return null your list is empty. So adjust your test.
Consider renaming the method name as well.
If thats not what you want, you'll need to change your implementation.
#Test
public void shouldReturnNullWhenPropertyIsNull() throws LoginException, JSONException {
when(valuemap.get("count", String.class)).thenReturn(null);
accordionModel.init();
assertTrue(accordionModel.getAccordionList().isEmpty());
}
java.lang.NumberFormatException: For input string: "count"
"count" can not be converted into an Integer. Try using your count variable ("6") instead.
You should check the content of the list, for now I adjusted it to check that the list has the correct size.
#Test
public void shouldReturnWhenPropertyNotNull() throws LoginException, JSONException {
when(valuemap.get("count", String.class)).thenReturn(count);
accordionModel.init();
assertEquals(Integer.valueOf(count), accordionModel.getAccordionList().size());
}
Note that generally the parameter order for assert's should be expected vs actual.

Response.entity returns NULL , instead it should return JSON RESPONSE

I am trying out hard to get that why the response .entity returns null but still not getting the answer what to do with it
in other examples i tried it returns the response but over here m not getting why null being received in the response
please help me out with the same
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;
import com.sun.jersey.spi.inject.Errors;
#Provider
public class GenericExceptionMapper implements ExceptionMapper<Throwable> {
#Override
public Response toResponse(Throwable ex) {
ErrorMessage errorMessage = new ErrorMessage();
errorMessage.setStatus(404);
errorMessage.setMessage(ex.getMessage());
return Response.status(Status.INTERNAL_SERVER_ERROR)
.entity(errorMessage).type(MediaType.APPLICATION_JSON_TYPE)
.build();
}
}

How to test #Valid

In my entities I have some hibernate annotations for validation, like #NotEmpty, #Pattern.. and others
In my controller, on save action, it has an #Valid parameter.
But if any entity has any required field, and there is no annotation I will have problems.
So I would like to test each entity, to ensure they have the necessary notes.
Something like:
#Test(expect=IllegalArgumentException.class)
public void testAllNull() {
Person p = new Persson(); // Person name has an #NotEmpty
validator.validate(p);
}
But how to validate it? Who is called to check #Valid?
Thanks.
I found out how to check:
#Autowired
private LocalValidatorFactoryBean validator;
...
validator.validateProperty(object, propertyName)
Here is a Spring v4.1.x based example of a test validating presence and processing of the #Valid annotation and building of custom JSON response in case of an error.
jUnit
import com.fasterxml.jackson.core.type.TypeReference;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.context.annotation.Bean;
import org.springframework.http.MediaType;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import javax.inject.Inject;
import java.util.List;
import static org.abtechbit.miscboard.util.JsonUtils.toJson;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.junit.Assert.assertThat;
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;
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(classes = {
RegistrationValidationTest.MockDependencies.class,
})
public class RegistrationValidationTest {
#Inject
MockMvc mvc;
#Test
public void validatesRegistration() throws Exception {
Registration registration = ... //build an invalid Registration object
MvcResult result = mvc.perform(post(RegistrationController.CONTEXT_REGISTER).
contentType(MediaType.APPLICATION_JSON).
content(toJson(registration))).
andExpect(status().isBadRequest()).
andExpect(content().contentType(MediaType.APPLICATION_JSON)).
andReturn();
assertThat(result.getResolvedException(), is(notNullValue()));
String content = result.getResponse().getContentAsString();
assertThat(content, is(notNullValue()));
List<Message> messages = JsonUtils.fromJson(content, new TypeReference<List<Message>>() {
});
assertThat(messages.size(), is(1));
}
public static class MockDependencies {
#Bean
public MockMvc mvc() {
return MockMvcBuilders.standaloneSetup(new RegistrationController()).build();
}
}
}
Controller
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.util.List;
import java.util.stream.Collectors;
#Controller
public class RegistrationController
{
public static final String CONTEXT_REGISTER = "/register";
#RequestMapping(value = CONTEXT_REGISTER, method = RequestMethod.POST)
#ResponseBody
public String register(#RequestBody #Valid Registration registration) {
//perform registration
}
#ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<List> handleValidationException(MethodArgumentNotValidException ex) {
//Build a list of custom Message{String message;} objects
List<Message> messages = ex.getBindingResult().getAllErrors().
stream().map(e->new Message(e.getDefaultMessage())).collect(Collectors.toList());
return ResponseEntity.status(HttpStatus.BAD_REQUEST).contentType(MediaType.APPLICATION_JSON).body(messages);
}
}
Spring MVC Test Framework might be a good choice. By using this, you can be assured that validations in your tests runs codes as Spring #MVC actually works.
Actually, the #Valid annotation is detected by HandlerMethodInvoker, which processes annotations on the handler methods of Spring controllers. Internally, the actual validation logic is delegated to the Validator bean depending on your application context settings. (Hibernate Validator is widely used.)
By default configuration (e.g. <mvc:annotation-driven />), LocalValidatorFactoryBean is used internally to process #Valid annotation as #Falci noted, but it may differ time to time. Instead, Spring MVC Test Framework provides the same environment as the main application uses, hence a good choice.