Testing spring redirect - junit

I want to add test for spring redirect. First I want to see response object. Here is question for same test : Test redirection Spring
#SpringBootTest
#AutoConfigureMockMvc
public class UserControllerTests {
#Autowired
private MockMvc mockMvc;
#Test
#WithMockUser(username = "myuser", authorities = "admin")
void whenAcceptShouldRedirectRoot() throws Exception {
this.mockMvc.perform(get("/user")).andDo(MockMvcResultHandlers.print());
}
}
#Controller
public class UserController {
#GetMapping("/user")
public String user() {
return "redirect:/user/general";
}
}
And I got the following error
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.IllegalStateException: Cannot send redirect - response is already committed
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1014)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:670)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)
at org.springframework.test.web.servlet.TestDispatcherServlet.service(TestDispatcherServlet.java:72)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:779)
at org.springframework.mock.web.MockFilterChain$ServletFilterProxy.doFilter(MockFilterChain.java:167)

Related

How to rollback Rabbit-mq message after Junit test?

When you test your code, you send a message to rabbit-mq. How do you get the message back when the test is over?
public interface RabbitProducer {
String OUTPUT = "rabbitmq_producer_channel";
#Output(OUTPUT)
MessageChannel output();
}
public class SysGroupServiceImpl {
#Autowired
private RabbitProducer rabbitProducer;
#Override
public Result remove(Collection<? extends Serializable> idList) {
rabbitProducer.output().send(MessageBuilder.withPayload(idList)
.setHeader("x-delay", 5000)
.setHeader("MessageType", "GroupBatchDelete").build());
return Result.booleanResult(true);
}
}
#SpringBootTest
#Transactional
#Rollback
public class SysGroupServiceTest {
#Autowired
private SysGroupService sysGroupService;
#Test
void removeTest(){
sysGroupService.remove(Stream.of("1").collect(Collectors.toList()));
}
}
I use Spring Cloud Stream to be compatible with RabbitMQ, and all the relevant code is there.Is there a way to mock this out?I tried the following scheme, but due to X-dealy, I got this error:No exchange type x-delayed-message
<dependency>
<groupId>com.github.fridujo</groupId>
<artifactId>rabbitmq-mock</artifactId>
</dependency>
#Component
public class RabbitMqMock {
#Bean
public ConnectionFactory connectionFactory() {
return new CachingConnectionFactory(MockConnectionFactoryFactory.build());
}
}
I know little about mocks. Can mocks create an X-delay exchange?

Expected a collection with size 2 but collection size was 0?

I'm writing some code to test a web service using mockito and junit, so I faced a problem within the hasSize(2). I have injected the controller and calling the method findAll which returns a list of Employees, but error persists, in debugging mode it told me that the collection was empty, however, it is not.
the error is:
java.lang.AssertionError: JSON path "$" Expected: a collection with
size <2> but: collection size was <0>
here is the class:
#RunWith(SpringJUnit4ClassRunner.class)
#SpringBootTest
public class GestionPointage3ApplicationTests {
private MockMvc mockMvc;
#InjectMocks
private EmployeController employeeController ;
#Mock
private EmployeService employeeService;
#Mock
private ModelMapper modelMapper;
#Before
public void setUp() throws Exception{
MockitoAnnotations.initMocks(this);
mockMvc=MockMvcBuilders.standaloneSetup(employeeController).build();
}
#Test
public void testgetAllEmployeeWithModelMapper() throws Exception{
Employe emp1 = new Employe("Hamza", "Khadhri", "hamza1007", "123");
Employe emp2 = new Employe("Oussema", "smi", "oussama", "1234");
List<Employe> Employees= Arrays.asList(emp1, emp2);
EmployeDTO dto1 = new EmployeDTO("Hamza", "Khadhri", "hamza1007", "123");
EmployeDTO dto2 = new EmployeDTO("Oussema", "smi", "oussama", "1234");
//when(modelMapper.map(emp1,EmployeDTO.class)).thenReturn(dto1);
// when(modelMapper.map(emp2,EmployeDTO.class)).thenReturn(dto2);
when(employeeService.findAll()).thenReturn(Employees);
mockMvc.perform(get("/employe/dto"))
.andExpect(status().isOk())
.andExpect(MockMvcResultMatchers.content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$", hasSize(2)))
.andExpect(jsonPath("$[0].nom", is("Hamza")))
.andExpect(jsonPath("$[0].prenom", is("Khadhri")))
.andExpect(jsonPath("$[0].login", is("hamza1007")))
.andExpect(jsonPath("$[0].mp", is("123")))
.andExpect(jsonPath("$[1].nom", is("Oussema")))
.andExpect(jsonPath("$[1].prenom", is("smi")))
.andExpect(jsonPath("$[1].login", is("oussama")))
.andExpect(jsonPath("$[1].mp", is("1234")));
verify(employeeService,times(1)).findAll();
verifyNoMoreInteractions(employeeService);
}
}
and this is the Controller:
#CrossOrigin(origins = "*", allowedHeaders = "*")
#RestController
#RequestMapping("/employe")
public class EmployeController {
#Autowired
private EmployeService employeService;
#Autowired
private ModelMapper modelMapper;
#GetMapping("/dto")
public List<Employe> findAll() throws Exception{
return employeService.findAllEmployeActive();
}
}
method signature:
public List<Employe>findAll() throws Exception;
public List<Employe>findAllEmployeActive() throws Exception;
StackTrace errors:
java.lang.AssertionError: Status expected:<200> but was:<500> at
org.springframework.test.util.AssertionErrors.fail(AssertionErrors.java:55)
at
org.springframework.test.util.AssertionErrors.assertEquals(AssertionErrors.java:82)
at
org.springframework.test.web.servlet.result.StatusResultMatchers.lambda$matcher$9(StatusResultMatchers.java:619)
at
org.springframework.test.web.servlet.MockMvc$1.andExpect(MockMvc.java:178)
at
com.cynapsys.pointage.GestionPointage3ApplicationTests.testgetAllEmployeeWithModelMapper(GestionPointage3ApplicationTests.java:66)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at
sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at
sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at
java.lang.reflect.Method.invoke(Unknown Source) at
org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at
org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at
org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at
org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at
org.springframework.test.context.junit4.statements.RunBeforeTestExecutionCallbacks.evaluate(RunBeforeTestExecutionCallbacks.java:73)
at
org.springframework.test.context.junit4.statements.RunAfterTestExecutionCallbacks.evaluate(RunAfterTestExecutionCallbacks.java:83)
at
org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at
org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
at..
You are mocking EmployeeService and telling the mocked instance to return the Employee list (with its two items) when the findAll() method is invoked:
when(employeeService.findAll()).thenReturn(Employees)
But in the EmployeeController you are actually invoking a different method on EmployeeService:
return employeService.findAllEmployeActive()
So, you should update your mocked expectation like so:
when(employeeService.findAllEmployeActive()).thenReturn(Employees)

How to write JUnit Test case

I am learning Junit testing on spring boot Application. my account controller method is depend on service class method. For that I used Mockito. I tried simple But here I am not getting how to write test case for following method? How I can use mockito.
can any one please help me for writing this test case?
AccountController
#RestController
#RequestMapping("/spacestudy/$ {InstituteIdentifier}/admin/account")
public class AccountController {
#Autowired
AccountService accService;
#GetMapping("/findAccountData")
public ResponseEntity<List<Tuple>> populateGridViews(#RequestParam(value="sClientAcctId",required=false) String sClientAcctId,
#RequestParam(value="sAcctDesc",required=false) String sAcctDesc,
#RequestParam(value="sInvestigatorName",required=false)String sInvestigatorName,
#RequestParam(value="sClientDeptId",required=false) String sClientDeptId) throws Exception {
return ResponseEntity.ok(accService.populateGridViews(sClientAcctId, sAcctDesc,sInvestigatorName,sClientDeptId));
}
}
AccountService
public List<Tuple> populateGridViews(String sClientAcctId, String sAcctDesc, String sInvestigatorName,
String sClientDeptId)throws Exception{
QAccount account = QAccount.account;
QDepartment department = QDepartment.department;
QAccountCPCMapping accountCPCMapping = QAccountCPCMapping.accountCPCMapping;
QInvestigator investigator = QInvestigator.investigator;
JPAQuery<Tuple> query = new JPAQuery<Tuple>(em);
query.select(Projections.bean(Account.class, account.sClientAcctId, account.sAcctDesc, account.sLocation,
Projections.bean(Department.class, department.sDeptName, department.sClientDeptId).as("department"),
Projections.bean(Investigator.class, investigator.sInvestigatorName).as("investigator"),
Projections.bean(AccountCPCMapping.class, accountCPCMapping.sCCPCode).as("accountCPC"))).from(account)
.innerJoin(account.department, department).innerJoin(account.accountCPC, accountCPCMapping)
.innerJoin(account.investigator, investigator);
if (StringUtils.isNotEmpty(sClientAcctId)) {
query.where(account.sClientAcctId.equalsIgnoreCase(sClientAcctId));
}
// code.......
return query.fetch();
}
AccountControllerTest
#RunWith(SpringRunner.class)
public class TestAccountController {
private MockMvc mockMvc;
#Mock
private AccountService accountService;
#InjectMocks
private AccountController accountController;
#Before
public void setup() {
mockMvc = MockMvcBuilders.standaloneSetup(accountController).build();
}
#Test
public void populateGridViewsTest() throws Exception {
//????
//????
}
}
It will be something like this:
#RunWith(SpringRunner.class)
public class TestAccountController {
private MockMvc mockMvc;
#Mock
private AccountService accountService;
#InjectMocks
private AccountController accountController;
#Before
public void setup() {
mockMvc = MockMvcBuilders.standaloneSetup(accountController).build();
}
#Test
public void populateGridViewsTest() throws Exception {
when(accountService.populateGridViews("foo","bar")).thenReturn(Arrays.asList(new Tuple("bazz"));
mockMvc.perform(get("/spacestudy/STACKOVERFLOW/admin/account/foo/bar"))
.andExpect(status().isOk())
.andExpect(jsonPath("someField").value("bazz"));
}
}
So basically you are replacing your service with mock and saying what it should return. In your particular case I don't see any reasons for unit testing this class, since it doesn't have any logic inside. But if you would have something like:
#GetMapping("/findAccountData")
public ResponseEntity<List<Tuple>> populateGridViews(...) throws Exception {
List<Tuple> result = accService.populateGridViews(...);
if(result==null){
return ResponseEntity.notFound();
}
return ResponseEntity.ok(result);
}
Then it would make more sense to test this class e.g.
1st test - mock your accService to return null and verify that response status is 404
2nd test - mock your accService to return not null and verify that response status is 200

Spring MVC jackson exception handling

Can I handle Jackson UnrecognizedPropertyException for a #RequestBody parameter? How can I configure this?
I'm working on a spring MVC project, and I use jackson as json plugin. Any mis-spell of the field name in a json request will lead to a error page, which should be a json string consist of error message. I'm a newbie to spring, and I think this error handling can be done with some spring configuration, but failed after several attempts. Any help?
Here is my mvc configure:
#EnableWebMvc
public class WebMvcConfig extends WebMvcConfigurerAdapter {
#Bean
public ViewResolver resolver() {
InternalResourceViewResolver bean = new InternalResourceViewResolver();
return bean;
}
#Override
public void configureDefaultServletHandling(
DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
}
My controller:
#RequestMapping(value = "/Login", method = RequestMethod.POST,
consumes="application/json", produces = "application/json")
public #ResponseBody AjaxResponse login(
#RequestBody UserVO user, HttpServletRequest request) {
//do something ...
}
Normal request json is:
{"Username":"123123", "Password":"s3cret"}
But if I send the following request:
{"Username":"123123", "pwd":"s3cret"}
which field name is mis-spell, then Spring catch this UnrecognizedPropertyException, and returned a error page, but I want to catch this exception and return a json string. How can I achieve this?
Use #ExceptionHandler annotation. Some documentation about it: http://spring.io/blog/2013/11/01/exception-handling-in-spring-mvc
#Controller
public class WebMvcConfig {
#RequestMapping(value = "/Login", method = RequestMethod.POST,
consumes="application/json", produces = "application/json")
public #ResponseBody AjaxResponse login(#RequestBody UserVO user, HttpServletRequest request) {
//do something ...
}
#ExceptionHandler(UnrecognizedPropertyException.class)
public void errorHandler() {
// do something. e.g. customize error response
}
}

JUnit: Unable to mock the RestTemplate object to call postForObject method

I am new to Mockito as well as Spring's RestTemplate. I am working on JUnit tests for a functionality which sends a request to a web-service and gets the response through the use of RestTemplate. I want the server to respond with a response that i want so that i can test the functionalities based on this response. I am using Mockito for mocking.
I am not sure where I am going wrong. Am I not creating proper mocks? Is my JSON object mapper not been configured properly?
Configuration file defining the RestTemplate bean:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<bean id="restTemplate" class="org.springframework.web.client.RestTemplate">
<property name="messageConverters">
<list>
<bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" />
<bean class="org.springframework.http.converter.xml.SourceHttpMessageConverter"/>
<bean class="org.springframework.http.converter.xml.MarshallingHttpMessageConverter">
<property name="marshaller" ref="xsStreamMarshaller" />
<property name="unmarshaller" ref="xsStreamMarshaller" />
</bean>
</list>
</property>
</bean>
<bean id="xsStreamMarshaller" class="org.springframework.oxm.xstream.XStreamMarshaller"></bean>
</beans>
My DTO's:
import org.codehaus.jackson.annotate.JsonWriteNullProperties;
#JsonWriteNullProperties(false)
public abstract class BaseDTO {
protected boolean error;
public boolean isError() {
return error;
}
public void setError(boolean error) {
this.error = error;
}
}
public class ChildDTO extends CommercialBaseDTO {
private String fullName;
public String getFullName() {
return fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
}
Class containing the method to test:
package com.exmpale.mypackage;
import org.springframework.web.client.RestTemplate;
#Component
public class MyUtilClass {
#Autowired
private RestTemplate restTemplate;
public RestTemplate getRestTemplate(){
return restTemplate;
}
public void setRestTemplate(RestTemplate restTemplate){
this.restTemplate = restTemplate;
}
// Method to test
public ChildDTO getChildDTO(MyUser myUser, HttpServletRequest request, HttpServletResponse response)
{
response.setContentType("application/json");
//Nothing much here, it takes the myUser and convert into childDTO
ChildDTO childDTO = new MyUtilClass().getDTOFromUser(request, myUser);
//This is the restTemplate that iam trying to mock.
childDTO = restTemplate.postForObject("http://www.google.com", childDTO, ChildDTO.class);
if (childDTO.isError()) {
//Then do some stuff.........
}
return childDTO;
}
}
The JUnit test class
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations={"test-config.xml"})
public class MyUtilClassTest {
#InjectMocks
RestTemplate restTemplate= new RestTemplate();
private MockRestServiceServer mockServer;
#Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
//Creating the mock server
//Add message conveters
List<HttpMessageConverter<?>> messageConverters = new ArrayList<HttpMessageConverter<?>>();
messageConverters.add(new FormHttpMessageConverter());
messageConverters.add(new StringHttpMessageConverter());
messageConverters.add(new MappingJacksonHttpMessageConverter());
//Create Object mapper
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure( DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
objectMapper.configure( SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS, false);
objectMapper.configure( SerializationConfig.Feature.AUTO_DETECT_FIELDS, true);
objectMapper.configure( SerializationConfig.Feature.AUTO_DETECT_GETTERS,true);
objectMapper.configure( SerializationConfig.Feature.AUTO_DETECT_IS_GETTERS,true);
MappingJacksonHttpMessageConverter jsonMessageConverter = new MappingJacksonHttpMessageConverter();
jsonMessageConverter.setObjectMapper(objectMapper);
messageConverters.add(jsonMessageConverter);
//Set the message converters
restTemplate.setMessageConverters(messageConverters);
mockServer = MockRestServiceServer.createServer(restTemplate);
}
#Test
public void testGetChildDTO()throws Exception {
MyUtilClass myUtil = new MyUtilClass();
MyUser myUser = new MyUser();
HttpServletRequest request = new HttpServletRequestWrapper(new MockHttpServletRequest());
HttpServletResponse response = new HttpServletResponseWrapper(new MockHttpServletResponse());
//create the mocks for ChildDTO. I want MyUtilClass().getDTOFromUser(request, myUser) to return this.
ChildDTO childDTOMock_One = Mockito.mock(ChildDTO);
//Want this to be returned when restTemplate.postForObject() is called.
ChildDTO childDTOMock_Two = Mockito.mock(ChildDTO.class);
childDTOMock_Two.setError(false);
//create the mocks for userMgntUtils
MyUtilClass myUtilClassMock = Mockito.mock(MyUtilClass.class);
//stub the method getDTOFromUser() to return the mock object. I need this mock to be passed to 'postForObject()'
Mockito.when(myUtilClassMock.getDTOFromUser(request, myUser)).thenReturn(childDTOMock_One);
String responseJSON="{\"error\":false}";
//set the expectation values for mockServer
mockServer.expect( requestTo("http://www.google.com")).andExpect(method(HttpMethod.POST)).andRespond(withSuccess(responseJSON,MediaType.APPLICATION_JSON));
//set the expectation values for restTemplate
Mockito.when(restTemplate.postForObject( "http://www.google.com", childDTOMock_One, ChildDTO.class)).thenReturn(childDTOMock_Two);
TypedUserDTO result = userMgmtUtils.getUserProfileDTO(registerUser, request, response, action);
assertNotNull(result);
}
}
Getting the following exception:
org.springframework.http.converter.HttpMessageNotWritableException:
Could not write JSON: No serializer found for class
org.mockito.internal.stubbing.defaultanswers.GloballyConfiguredAnswer
and no properties discovered to create BeanSerializer (to avoid
exception, disable SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS) )
(through reference chain:
com.biogenidec.dto.TypedUserDTO$$EnhancerByMockitoWithCGLIB$$bee3c447["callbacks"]->org.mockito.internal.creation.MethodInterceptorFilter["handler"]->org.mockito.internal.handler.InvocationNotifierHandler["mockSettings"]->org.mockito.internal.creation.settings.CreationSettings["defaultAnswer"]);
nested exception is org.codehaus.jackson.map.JsonMappingException: No
serializer found for class
org.mockito.internal.stubbing.defaultanswers.GloballyConfiguredAnswer
and no properties discovered to create BeanSerializer (to avoid
exception, disable SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS) )
(through reference chain:
com.biogenidec.dto.TypedUserDTO$$EnhancerByMockitoWithCGLIB$$bee3c447["callbacks"]->org.mockito.internal.creation.MethodInterceptorFilter["handler"]->org.mockito.internal.handler.InvocationNotifierHandler["mockSettings"]->org.mockito.internal.creation.settings.CreationSettings["defaultAnswer"])
And:
Caused by: org.codehaus.jackson.map.JsonMappingException: No serializer found for class org.mockito.internal.stubbing.defaultanswers.GloballyConfiguredAnswer and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS) ) (through reference chain: com.biogenidec.dto.TypedUserDTO$$EnhancerByMockitoWithCGLIB$$bee3c447["callbacks"]->org.mockito.internal.creation.MethodInterceptorFilter["handler"]->org.mockito.internal.handler.InvocationNotifierHandler["mockSettings"]->org.mockito.internal.creation.settings.CreationSettings["defaultAnswer"])
The idea of Mockito is to test the class and none of the dependencies outside of it. So if your testing MyUtilClass you want to mock the RestTemplate class. And your #InjectMocks is on the wrong class see below.
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations={"test-config.xml"})
public class MyUtilClassTest
{
#Mock
private RestTemplate restTemplate;
#InjectMocks
private MyUtilClass myUtilClass;
#Before
public void setUp() throws Exception
{
MockitoAnnotations.initMocks(this);
}
#Test
public void testGetChildDTO()throws Exception
{
MyUser myUser = new MyUser();
HttpServletRequest request = new HttpServletRequestWrapper(new MockHttpServletRequest());
HttpServletResponse response = new HttpServletResponseWrapper(new MockHttpServletResponse());
Mockito.when(RestTemplate.postForObject(Mockito.eq("http://www.google.com",
Mockito.any(ChildDTO.class), Mockito.eq(ChildDTO.class)))).thenAnswer(
new Answer<ChildDTO>()
{
#Override
public ChildDTO answer(InvocationOnMock invocation) throws Throwable
{
//The below statement takes the second argument passed into the method and returns it
return (ChildDTO) invocation.getArguments()[1];
}
});
ChildDTO childDTO = myUtilClass.getDTOFromUser(request, myUser);
//then verify that the restTemplate.postForObject mock was called with the correct parameters
Mockito.verify(restTemplate, Mockito.times(1)).postForObject(Mockito.eq("http://www.google.com",
Mockito.eq(childDTO), Mockito.eq(ChildDTO.class));
}
}
Also I find it bad practice to test other frameworks classes, more often then not they already tested their class and your just duplicating their work.
As correctly noted above, to test your method with mockito, it is not necessary to initialize restTemplate.
It is enough to verify that the parameters of the input are correct (if needed) and return the correct mocking object from restTemplate.
We do not test the restTemplate here, we only test our code. This is the purpose of unit tests.
You can do something like this, or something simpler:
#RunWith(value = MockitoJUnitRunner.class)
public class Test {
#InjectMocks
private MyUtilClass testObj;
#Mock
private RestTemplate restTemplate;
#Mock
MyUser myUser;
#Mock
HttpServletRequest request;
#Mock
HttpServletResponse response;
#Test
public void test() throws Exception {
//Configure sample to comparison and verification the result of the method:
ChildDTO sample = getSample();
//configure mocks:
ChildDTO myObject = new ChildDTO();
//configure myObject properties
ResponseEntity<ChildDTO> respEntity = new ResponseEntity<>(
myObject, HttpStatus.ACCEPTED);
when(restTemplate.postForObject(anyString(), Matchers.<HttpEntity<?>>any(),
Matchers.any(Class.class))).thenReturn(respEntity);
//other stuff to configure correct behaviour of mocks request, response e.t.c.
//act:
ChildDTO result = testObj.getChildDTO(myUser, request, response);
//verify that correct parameters were passed into restTemplate method "postForObject":
verify(restTemplate).postForObject(eq("http://www.google.com"), Matchers.<HttpEntity<?>>any(),
eq(ChildDTO.class)).thenReturn(respEntity);
//assert to verify that we got correct result:
assertEquals(sample, result);
}
}