How to mock RestTemplate exchange? - spring

I want to unit test assignApplicationsToUser. A list of applicationId and user id is given and I have a URL to validate a user. I am getting an exception mentioned below.
java.lang.NullPointerException: Cannot invoke "com.fasterxml.jackson.databind.JsonNode.asText()" because the return value of "com.fasterxml.jackson.databind.JsonNode.get(String)" is null
AssignmentService.java
public class AssignmentService implements AssignemetServiceInterface {
#Autowired
AppInterceptor appInterceptor;
#Autowired
AssignmentRepository assignmentRepository;
#Autowired
private RestTemplate restTemplate;
private String uri="http://localhost:8080/api/users/"+uuid;
#Override
public List<String> assignApplicationsToUser(List<String> applications, String uuid)
throws SQLException, RequestEntityNotFoundException {
HttpHeaders headers = new HttpHeaders();
headers.set("token", appInterceptor.getLoggedInUser());
HttpEntity<String> requestEntity = new HttpEntity<>(null, headers);
String result = restTemplate.exchange(uri, HttpMethod.GET, requestEntity, String.class).getBody();
ObjectMapper objectMapper = new ObjectMapper();
List<String> response = new ArrayList<>();
JsonNode responseJson = objectMapper.readTree(result);
if (responseJson.get("data") == null
&& responseJson.get("error").get("status").asText().equals("NOT_FOUND")) {
throw new RequestEntityNotFoundException(uuid, "find");
}
for (String application : applications) {
ApplicationAssignment isAssigned = assignmentRepository.findOneByApplicationId(application);
if (isAssigned != null) {
isAssigned.setIsUser(true);
response.add(application + " reassigned to "+ uuid);
isAssigned.setAssignedTo(uuid);
this.assignmentRepository.save(isAssigned);
}
else {
ApplicationAssignment newApplication = new ApplicationAssignment(application, uuid, true);
this.assignmentRepository.save(newApplication);
response.add(application + " assigned successfully");
}
}
return response;
}
}
sample input:
{
applications :["APP001","APP002","APP003","APP004"],
uuid : "user1"
}
Edited :
I have added sample response for the same.
{
"data": {
"id": "fa727274-5a74-428a-b0f6-501eebafd8e8",
"name": "Akash",
"email": "AkashTyagi#fico.com",
"phone": 8799190991,
"isActive": true,
"createdBy": "abhishekjaiswal#fico.com",
"updatedBy": null,
"creationTimeStamp": "2021-08-11T11:23:05.356+00:00",
"updationTimeStamp": null
},
"error": null,
"timeStamp": "2021-08-16T05:02:04.866+00:00",
"success": true
}
AssignmentServiceTest.java
#RunWith(MockitoJUnitRunner.class)
#SpringBootTest
public class AssignmentServiceTest {
private static final Logger LOGGER = LoggerFactory.getLogger(AssignmentServiceTest.class);
#InjectMocks
private AssignmentService assignmentService;
#Mock
private AssignmentRepository assignmentRepo;
#Mock
private AppInterceptor appInterceptor;
#Mock
private RestTemplate restTemplate;
ObjectMapper objectMapper;
String jsonString="{\r\n"
+ " \"data\": {\r\n"
+ " \"id\": \"fa727274-5a74-428a-b0f6-501eebafd8e8\",\r\n"
+ " \"name\": \"Akash\",\r\n"
+ " \"email\": \"AkashTyagi#fico.com\",\r\n"
+ " \"phone\": 8799190991,\r\n"
+ " \"isActive\": true,\r\n"
+ " \"createdBy\": \"abhishekjaiswal#fico.com\",\r\n"
+ " \"updatedBy\": null,\r\n"
+ " \"creationTimeStamp\": \"2021-08-11T11:23:05.356+00:00\",\r\n"
+ " \"updationTimeStamp\": null\r\n"
+ " },\r\n"
+ " \"error\": null,\r\n"
+ " \"timeStamp\": \"2021-08-16T05:02:04.866+00:00\",\r\n"
+ " \"success\": true\r\n"
+ "}";;
JsonNode mock;
#BeforeEach
private void setUp() throws JsonMappingException, JsonProcessingException {
objectMapper = new ObjectMapper();
mock = org.mockito.Mockito.mock(JsonNode.class);
}
#Test
public void test_assignApplicationsToUser() throws NullPointerException, SQLException, RequestEntityNotFoundException, IndexOutOfBoundsException,JsonProcessingException, URISyntaxException{
LOGGER.info("Begin of test_assignApplicationToUser method");
ApplicationAssignment applicationAssignment = new ApplicationAssignment("1","u1",true);
ApplicationAssignment savedApplicationAssignment = new ApplicationAssignment("1","u2",true);
ResponseEntity<String> myEntity = new ResponseEntity<String>("{\r\"error\":null\r}",HttpStatus.ACCEPTED);
Mockito.when(restTemplate.exchange(
ArgumentMatchers.anyString(),
ArgumentMatchers.any(HttpMethod.class),
ArgumentMatchers.any(),
ArgumentMatchers.<Class<String>>any())).thenReturn(myEntity);
Mockito.when(appInterceptor.getLoggedInUser()).thenReturn("abhishek#fico.com");
Mockito.when(mock.get("data")).thenReturn(mock);
Mockito.when(mock.get("error")).thenReturn(mock);
Mockito.when(mock.get("error").asText()).thenReturn("FOUND");
LOGGER.info("Node value "+ mock.asText());
Mockito.when(assignmentRepo.findOneByApplicationId("1")).thenReturn(applicationAssignment);
Mockito.when(assignmentRepo.save(ArgumentMatchers.any())).thenReturn(savedApplicationAssignment);
// Mock the input List of applications
List<String> listOfApplication = new ArrayList<>();
listOfApplication.add("app1");
listOfApplication.add("app2");
List<String> response = assignmentService.assignApplicationsToUser(listOfApplication,"u1");
assertEquals(response.get(0),"app1 assigned successfully");
}
}

In main code, create two pojos as below which would represent response of the rest call.
#JsonIgnoreProperties(ignoreUnknown = true)
public class UserDataResponse {
#JsonProperty("data")
UserInfo userInfo;
#JsonProperty("error")
String error;
#JsonProperty("success")
boolean success;
}
#JsonIgnoreProperties(ignoreUnknown = true)
public class UserInfo {
#JsonProperty("id")
String id;
#JsonProperty("name")
String name;
#JsonProperty("email")
String email;
#JsonProperty("phone")
String phone;
#JsonProperty("isActive")
boolean isActive;
#JsonProperty("createdBy")
String createdBy;
#JsonProperty("updatedBy")
String updatedBy;
}
In AssignmentService class change your code to get the response as below since this is better way to handle the rest response based on the HttpStatus code rather than trying to element in the json. So your main rest call would look like as below:
String result = restTemplate.exchange(uri, HttpMethod.GET, requestEntity, String.class);
if(result.getStatusCode()==HttpStatus.OK){
UserDataResponse userDataResponse = readResponse(result,UserDataResponse.class);
}else if(result.getStatusCode()==HttpStatus.NOT_FOUND){
throw new RequestEntityNotFoundException(uuid, "find");
}
// You can make below code as part of the helper class and use it anywhere you want.
private <T> T readResponse(ResponseEntity<String> responseEntity,Class<T> classType){
T object;
try {
object = objectMapper.readValue(responseEntity.getBody(),classType);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return null;
}
Testing Code:
Mock all the variables of service like AppInterceptor, repository and resttemplate to be injectto AssignmentService.
Put all the below code in test class like AssingmentServiceTest
#Mock
AppInterceptor appInterceptor;
#Mock
AssignmentRepository assignmentRepository;
#Mock
RestTemplate restTemplate;
#InjectMocks
AssignmentService assignmentService;
ObjectMapper objectMapper = new ObjectMapper();
#Test
public void test_assignApplicationsToUser(){
UserDataResponse restResponse = new UserDataResponse();
String jsonString="{\r\n"
+ " \"data\": {\r\n"
+ " \"id\": \"fa727274-5a74-428a-b0f6-501eebafd8e8\",\r\n"
+ " \"name\": \"Akash\",\r\n"
+ " \"email\": \"AkashTyagi#fico.com\",\r\n"
+ " \"phone\": 8799190991,\r\n"
+ " \"isActive\": true,\r\n"
+ " \"createdBy\": \"abhishekjaiswal#fico.com\",\r\n"
+ " \"updatedBy\": null,\r\n"
+ " \"creationTimeStamp\": \"2021-08-11T11:23:05.356+00:00\",\r\n"
+ " \"updationTimeStamp\": null\r\n"
+ " },\r\n"
+ " \"error\": null,\r\n"
+ " \"timeStamp\": \"2021-08-16T05:02:04.866+00:00\",\r\n"
+ " \"success\": true\r\n"
+ "}";
restResponse = readResponse(jsonString, UserDataResponse.class);
ResponseEntity<String> myEntity = new ResponseEntity<String>(restResponse.toString(),HttpStatus.OK);
Mockito.when(resttemplate.exchange(
ArgumentMatchers.anyString(),
ArgumentMatchers.any(HttpMethod.class),
ArgumentMatchers.any(),
ArgumentMatchers.<Class<String>>any())
).thenReturn(myEntity);
// You can create a ApplicationAssignment pojo and pass it in thenReturn
ApplicationAssignment applicationAssignment = new ApplicationAssingment(1,"sd");
Mockito.when(assignmentRepository.findOneByApplicationId(ArgumentMatchers.any())).thenReturn(assignmentRepository);
Mockito.when(appInterceptor.getLoggedInUser).thenReturn("token");
// You can mock the response here but looks like that response is not used anywhere
ApplicationAssignment savedApplicationAssignment = new ApplicationAssignment(1,"ss");
Mockito.when(assignmentRepository.save(ArgumentMatchers.any())).thenReturn(savedApplicationAssignment);
// Mock the input List of applications
List<String> listOfApplication = new ArrayList<>();
listOfApplication.add("app1");
listOfApplication.add("app2");
List<String> response = assignmentService.assignApplicationsToUser(listOfApplication,"1212");
assertEquals(response[0],"app1 reassigned to 1212");
}

Related

Take the sum of the query result as separate data

Etity
#Entity
public class DateFMail {
#Id
private double balance;
public DateFMail() {
}
public DateFMail(double balance) {this.balance = balance;}
public DateFMail(DateFMail dateFMail) {
}
public double getBalance() { return balance;}
#Override
public String toString() {
return "DateFMail{" +
"balance=" + balance +
'}';
}
}
Service
public interface DateFMailService {
List<DateFMail> findAll();
}
Impl
#Service
public class DateFMailServiceImpl implements DateFMailService {
#Autowired
private DateFMailRepository mailRepository;
#Override
public List<DateFMail> findAll() {
return mailRepository.findAll();
}
}
Repository
#Repository
public interface DateFMailRepository extends JpaRepository<DateFMail, Long> {
#Query(value = "SELECT SUM(balance) \n" +
" FROM agents", nativeQuery = true)
List<DateFMail> findAll();
}
Mail Seder
#Service
public class EmailDos {
#Autowired
private JavaMailSender mailSender;
private DateFMailRepository mailRepository;
String fileDate1 = new SimpleDateFormat("dd.MM.yyyy").format(new Date());
LocalDate today = LocalDate.now();
String fileDate = (today.minusDays(1)).format(DateTimeFormatter.ofPattern("dd MMM"));
String fileDate2 = (today.minusMonths(1)).format(DateTimeFormatter.ofPattern("MMM"));
public void sendMailSum(String from, String to, String subject, String body, String fileToAttach) throws SQLException {
List<DateFMail> list = new ArrayList<>(mailRepository.findAll());
List<DateFMail> list1 = list.stream()
.map(DateFMail::new)
.collect(Collectors.toList());
System.out.println("sending email...................");
System.out.println(list1);
MimeMessagePreparator preparator = new MimeMessagePreparator() {
public void prepare(MimeMessage mimeMessage) throws Exception {
mimeMessage.setFrom(new InternetAddress(from));
mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
mimeMessage.setSubject(subject);
mimeMessage.setText(body);
FileSystemResource file = new FileSystemResource(new File("C:...xlsx"));
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
helper.setFrom("SomeAddress#gmail.com");
helper.setTo(InternetAddress.parse("SomeAddress#gmail.com"));
helper.setText("Good day!\nIn attachment payments for " + fileDate + " с 12.00-00.00" + "\nAmount for " + fileDate1 + list1);
helper.addAttachment("...xlsx", file);
mailSender.send(mimeMessage);
System.out.println("email Fab was successfully sent.....");
}
};
try {
mailSender.send(preparator);
} catch (MailException ex) {
System.err.println(ex.getMessage());
}
}
}
Controller
#Component
public class DateFMailController {
#Autowired
private DateFMailService mailService;
public void saveSum() throws IOException {
saveExcel(mailService.findAll(), "....xlsx");
}
private void saveExcel(List<DateFMail> list, String fileName) throws IOException {
Workbook workbook = new XSSFWorkbook();
CreationHelper createHelper = workbook.getCreationHelper();
Sheet sheet = workbook.createSheet("ECards");
sheet.autoSizeColumn(0);
Row header = sheet.createRow(0);
CellStyle headerStyle = workbook.createCellStyle();
headerStyle.setFillForegroundColor(IndexedColors.LIGHT_BLUE.getIndex());
headerStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
XSSFFont font = ((XSSFWorkbook) workbook).createFont();
font.setFontName("Arial");
font.setFontHeightInPoints((short) 10);
font.setBold(true);
headerStyle.setFont(font);
Cell headerCell = header.createCell(0);
headerCell.setCellValue("Sum");
headerCell.setCellStyle(headerStyle);
CellStyle style = workbook.createCellStyle();
style.setWrapText(true);
int ix_row=2;
for (DateFMail dateFMail : list) {
Row row = sheet.createRow(ix_row);
Cell cell = row.createCell(0);
cell.setCellValue(dateFMail.getBalance());
cell.setCellStyle(style);
ix_row++;
}
FileOutputStream outputStream = new FileOutputStream(fileName);
workbook.write(outputStream);
workbook.close();
}
}
Save Runer
#Component
public class SaveCardsStartupRunner implements ApplicationRunner {
#Autowired
private ECardController eCardController;
private DateFMailController controller;
// #Autowired
// private EmailDos emailDos;
String fileDate1 = new SimpleDateFormat("dd.MM.yyyy").format(new Date());
LocalDate today = LocalDate.now();
String fileDate = (today.minusDays(1)).format(DateTimeFormatter.ofPattern("dd MMM"));
String fileDate2 = (today.minusMonths(1)).format(DateTimeFormatter.ofPattern("MMM"));
#Override
public void run(ApplicationArguments args) throws Exception {
eCardController.saveCards();
controller.saveSum();
}
}
I have corrected my question. I've pasted all the code here that pertains to my question. For starters, I would like to simply output the Query result of the repository to the console. But in the form that I just posted here, I get a NullPointerException error and says that in a part of the code: controller.saveSum (); - controller = null.
Create a PaymentService class which should contain the method getTotalPayment. Inject this class in EmailSend (tip: please change this class name from EmailSend to EmailSender as class names should be noun) class. And then in PaymentService Class you should interact Data Repository class. Call this getTotalPayment method from the EmailSend class.

Test multipart PUT request with json data using mockMvc

I am trying to unit test a put request which takes a file and some json data as request body. following is the method i am trying to test:
#RequestMapping(
value = "/{id}",
method = RequestMethod.PUT,
produces = { "application/json" }
)
public ResponseEntity<UpdateT1Output> update(#PathVariable String id, #ModelAttribute #Valid UpdateT1Input t1) {
// implementation here
}
UpdateT1Input.java
public class UpdateT1Input {
private char[] ca;
private byte[] file;
public void setFile(MultipartFile mpfile) {
try {
file = mpfile.getBytes();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private List<Double> flpa;
private List<Double> fpa;
#NotNull(message = "id Should not be null")
private Long id;
private String str;
private Long versiono;
}
test setup
#Test
public void UpdateT1_T1Exists_ReturnStatusOk() throws Exception {
// create entity obj with default values
T1Entity entity = createUpdateEntity();
entity.setVersiono(0L);
UpdateT1Input t1Input = new UpdateT1Input();
t1Input.setId(entity.getId());
t1Input.setFlpa(entity.getFlpa());
t1Input.setStr(entity.getStr());
ObjectWriter ow = new ObjectMapper()
.registerModule(new JavaTimeModule())
.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
.writer()
.withDefaultPrettyPrinter();
String json = ow.writeValueAsString(t1Input);
MockMultipartHttpServletRequestBuilder builder =
MockMvcRequestBuilders.multipart("/t1/" + entity.getId());
builder.with(request -> {
request.setMethod("PUT");
return request;
});
mvc.perform(builder
.file("file", "ABC".getBytes("UTF-8"))
.content(json)
.contentType(MediaType.APPLICATION_JSON)
)
.andExpect(status().isOk());
}
but in controller only id and file fields are set in input dto all other fields are null. i am using #ModelAttribute to avoid dividing request into file and data parts. so is there a way that to get all the fields in single object?

How to replace placeholder message with #Email annotation

I know how to replace placeholders with actual values in Spring, and things are working for me in my application but my question is specific to below usecase.
Is it even possible to have ${malformed.email.address} replaced by actual value from properties file?
#RequestMapping(value = "/forgot-password", method = RequestMethod.POST)
public ResponseEntity<String> forgotPassword(#RequestBody #Email(message = "${malformed.email.address}") #NotNull String emailAddress, UriComponentsBuilder ucBuilder) {
System.out.println("Forgot password for User : " + emailAddress);
try {
userService.forgotPassword(emailAddress);
return new ResponseEntity<String>("If " + emailAddress + " existed then you should receive an email soon.", HttpStatus.OK);
} catch (ServiceException e) {
throw new ControllerRuntimeException(e);
}
}
I have this configured :
#Bean
public MethodValidationPostProcessor methodValidationPostProcessor() {
return new MethodValidationPostProcessor();
}
and I have messages.properties file in the classpath and spring's Environment object is populated.
This is my Exception Handler :
#ControllerAdvice
public class ConstraintViolationExceptionHandler {
#ExceptionHandler(ConstraintViolationException.class)
#ResponseBody
#ResponseStatus(HttpStatus.BAD_REQUEST)
public String handleValidationException(ConstraintViolationException e) {
for (ConstraintViolation<?> s : e.getConstraintViolations()) {
return s.getInvalidValue() + ": " + s.getMessage();
}
return "Invalid request supplied";
}
}
This is what I get as a response :
WARN | 2019-02-05 00:21:16,622 |
org.hibernate.validator.internal.engine.messageinterpolation.ElTermResolver | HV000129: EL expression '${malformed.email.address}' references an unknown
property
javax.el.PropertyNotFoundException: ELResolver cannot handle a null base
Object with identifier [malformed]
at org.apache.el.parser.AstIdentifier.getValue(AstIdentifier.java:120)
at org.apache.el.parser.AstValue.getValue(AstValue.java:137)
at org.apache.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:184)
at org.hibernate.validator.internal.engine.messageinterpolation.ElTermResolver.interpolate(ElTermResolver.java:65)
at org.hibernate.validator.internal.engine.messageinterpolation.InterpolationTerm.interpolate(InterpolationTerm.java:64)
at org.hibernate.validator.messageinterpolation.ResourceBundleMessageInterpolator.interpolate(ResourceBundleMessageInterpolator.java:75)
at org.hibernate.validator.messageinterpolation.AbstractMessageInterpolator.interpolateExpression(AbstractMessageInterpolator.java:387)
at org.hibernate.validator.messageinterpolation.AbstractMessageInterpolator.interpolateMessage(AbstractMessageInterpolator.java:344)

Testing RestTemplate in SpringBoot

I am trying to test the class bellow which is a Spring Batch reader.
My test returns a null when response.getBody() is invoked from the test in test.
My java class :
#Value("${rest.basepath}")
private String apiURI;
private int nextEmailIndex;
private RestTemplate restTemplate;
private List<EmailEntity> EmailEntityIterator;
private static final Logger logger = Logger.getLogger(EmailItemReader.class.getName());
/**
* Constructor
* #param restTemplate
* The RestTemplate class allows us to call a
* rest end point within the batch
*/
EmailItemReader(RestTemplate restTemplate) {
this.restTemplate = restTemplate;
nextEmailIndex=0;
}
/**
* Checks if the list of emails is empty
* Populates it by fetching unread emails
* #return EmailEntity
*/
#Override
public EmailEntity read(){
if (isEmailEntityInitialised()) {
EmailEntityIterator = fetchEmails();
}
EmailEntity nextEmail = null;
if (nextEmailIndex < EmailEntityIterator.size() && nextEmailIndex < 50) {
nextEmail = EmailEntityIterator.get(nextEmailIndex);
nextEmailIndex++;
}
System.out.println("The email index :- " + nextEmailIndex);
return nextEmail;
}
/**
* Returns a list of unread emails
* #return List<EmailEntity>
*/
private List<EmailEntity> fetchEmails() {
restTemplate.setMessageConverters(getMessageConverters());
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setAccept(Arrays.asList(MediaType.APPLICATION_JSON_UTF8));
HttpEntity<String> entity = new HttpEntity<>(httpHeaders);
ResponseEntity<EmailEntity[]> response =
restTemplate.exchange(apiURI, HttpMethod.GET, entity, EmailEntity[].class, 100);
EmailEntity[] partialEmailEntity = response.getBody();
List<EmailEntity> partialEmailEntityList = Arrays.asList(partialEmailEntity);
List<EmailEntity> EmailEntityList = new ArrayList<>();
for (EmailEntity EmailEntity: partialEmailEntityList) {
logger.info("The UUID :" + EmailEntity.getUuid() );
ResponseEntity<EmailEntity> fullResponce =
restTemplate.exchange(apiURI+EmailEntity.getUuid(), HttpMethod.GET, entity, EmailEntity.class, 100);
EmailEntity fullEmail = fullResponce.getBody();
EmailEntityList.add(fullEmail);
logger.info("The full email : "+ fullEmail);
}
printEmailsToLogs(EmailEntityList);
return EmailEntityList;
}
** Please see my test bellow, I have tried to mock my restTemplate but the response still returns will a null pointer**
#ContextConfiguration
#TestExecutionListeners( { DependencyInjectionTestExecutionListener.class,
StepScopeTestExecutionListener.class })
#RunWith(SpringJUnit4ClassRunner.class)
public class EmailItemReaderTest {
#Mock
private RestTemplate restTemplate;
#InjectMocks
private EmailItemReader reader;
#Before
public void setUp(){
MockitoAnnotations.initMocks(this);
}
#Test
public void read() {
PlainContent plainContent = new PlainContent();
plainContent.setData("test");
RawEmail rawEmail = new RawEmail();
rawEmail.setData("Raw email");
EmailEntity mockEntity1 = new EmailEntity();
mockEntity1.setBody(plainContent);
mockEntity1.setContactNumberRequired(true);
mockEntity1.setContactNumber("0000000000");
mockEntity1.setStructured(true);
mockEntity1.setSubjectActive(true);
mockEntity1.setConfigEmailSubjectId(1);
mockEntity1.setSubjectLine("subject");
mockEntity1.setRawEmail(rawEmail);
EmailEntity[] testArray = new EmailEntity[1];
testArray[0] = mockEntity1;
ResponseEntity<EmailEntity[]> mockEntity = Mockito.spy(new ResponseEntity(HttpStatus.OK));
Mockito.doReturn(mockEntity).when(restTemplate).exchange(
Mockito.any(URI.class),
Mockito.any(HttpMethod.class),
Mockito.any(HttpEntity.class),
Mockito.eq(Class[].class)
);
reader.read();
Mockito.verify(restTemplate).exchange(Mockito.any(URI.class),Mockito.any(HttpMethod.class),Mockito.any(HttpEntity.class), Mockito.eq(EmailEntity[].class));
}
}
Please assist with any information or suggestions that can help. Thank in advance.
Finaly solved the issues : My response was not null, but my response body was null. So I threw in mock data for the response to return.
So I replaced this:
EmailEntity[] testArray = new EmailEntity[1];
testArray[0] = mockEntity1;
ResponseEntity<EmailEntity[]> mockEntity = Mockito.spy(new ResponseEntity(HttpStatus.OK));
with this :
EmailEntity[] testArray = new EmailEntity[1];
testArray[0] = mockEntity1;
ResponseEntity<EmailEntity[]> mockPartialEntity = Mockito.spy(new ResponseEntity<>(emailEntities, HttpStatus.OK));

Spring Rest Issue

I am getting an error while i am trying to test my "testCreateUser" method using Spring RestApi, the uploadNewUser.xml contains the login information about the user and the role.
#Test
public void testCreateUser() throws Exception {
Reader reader = getFileReader("src/test/resources/uploadNewUser.xml");
String input_xml = IOUtils.toString(reader);
byte[] content = input_xml.getBytes();
request.addHeader("Accept", "application/xml");
request.addHeader("Content-Type", "application/xml");
request.setContent(content);
request.setContentType("text/xml");
request.setMethod(RequestMethod.POST.name());
request.setRequestURI("/restapi/users/");
final ModelAndView mav = handle(request, response);
Map<String, Object> map = mav.getModel();
for (Entry<String, Object> entry : map.entrySet()) {
String key = entry.getKey();
UserCollection collection = (UserCollection) entry.getValue();
org.springframework.validation.BindingResult.error = com.xxx.dashboard.restapi.GlobalResponse#42a4fd6d
error stack:
java.lang.ClassCastException: com.xxx.dashboard.restapi.GlobalResponse cannot be cast to com.xxx.dashboard.restapi.UserCollection
and i am getting an issue with cannot cast GlobalRespose to UserCollection. can anyone tell me where exactly i am doing is wrong? any help or pointers are most welcome thanks in advance
#Controller("userrestapi")
#RequestMapping(value = { "/restapi/users/", "/restapi/users" })
public class UserRestApi extends AbstractBaseApi {
...
#RequestMapping(method = RequestMethod.POST)
#ResponseStatus(value = HttpStatus.CREATED)
public ModelAndView createNewUser(#RequestBody UserCollection userCollection,
#RequestHeader(value = "accept", required = false) String accept,
#RequestHeader(value = "version", required = false) String version) {
try {
OOUser ooUser = userCollection.getUsers().get(0);
Mapper mapper = (Mapper) userVersions.get(Constants.USER_DETAIL_VERSION_MAPPER_KEY);
int userId = usersRestApiService.validateAndCreateNewUser(ooUser, mapper);
List<FilterField> filterFieldList = new ArrayList<FilterField>();
filterFieldList.add(new FilterField("userId", String.valueOf(userId)));
return getUserDetailsForFilter(filterFieldList, accept, version, mapper);
} catch (Exception ex) {
logger.warn("Api exception", ex);
return getModelAndView(accept, "error", getGlobalResponse(ex));
}
the abstractbaseapi contains following
public class AbstractBaseApi {
public static final String XML_VIEW = "apiXmlView";
public static final String JSON_VIEW = "apiJsonView";
public static final String JSON_ACCEPT_HEADER = "application/json";
public static final String JSON_CONTENT_HEADER = "Content-type: application/json";
public static final String XML_CONTENT_HEADER = "Content-type: text/html;charset=utf-8";
public static final int MAX_COUNT = 100;
public static final String XML_REQUEST_ERROR_FORMAT = "<?xml version='1.0' encoding='UTF-8'?><GlobalResponse xmlns='http://www.operative.com/api' xmlns:v2='http://www.operative.com/api/v2' xmlns:v1='http://www.operative.com/api/v1'> <error errorCode='%1$s' text='%2$s'/> </GlobalResponse>";
public static final String JSON_REQUEST_ERROR_FORMAT = "{error:{errorCode:'%1$s',text:'%2$s'}}";
protected final Logger logger = Logger.getLogger(this.getClass());
protected ModelAndView getModelAndView(String accept, String key, Object value) {
String view = XML_VIEW;
if (accept != null && accept.toLowerCase().contains(JSON_ACCEPT_HEADER)) {
view = JSON_VIEW;
}
if (logger.isDebugEnabled()) {
logger.debug("Accept Header:" + accept + " , generating:" + view);
}
return new ModelAndView(view, BindingResult.MODEL_KEY_PREFIX + key, value);
}
Your model contains more than you think.
You are going through your model and looking for your user collection. However, the first encountered object in your map seems to be the GlobalResponse map.
You should probably just get it by name from the model, i.e.
UserCollection collection = (UserCollection) mav.getModel().get("userCollection");
rather than iterating..

Resources