Spring Integration - How to mock input-channel - junit

I am new to Spring Integration so please forgive and correct me if my question is absurd. I am trying to write Unit test cases for Spring Integration application where I am testing only controller and looking to mock service call.
Test:
#RunWith(PowerMockRunner.class)
#PrepareForTest({HeaderUtils.class})
#PowerMockIgnore({ "javax.management.*", "javax.script.*" })
public class DocMgmtImplTestPower {
private MockMvc mvc;
#InjectMocks
private DocMgmtImpl docMgmtImpl;
#Mock
DocMgmtService docMgmtServiceGateway;
#Mock
SendComnMsgResponse sendComnMsgResponse;
#Before
public void init() {
MockitoAnnotations.initMocks(this); //
mvc = MockMvcBuilders.standaloneSetup(DocMgmtImpl.class).build();
PowerMockito.mockStatic(HeaderUtils.class, new Answer<Map<String, Object>>() {
#Override
public Map<String, Object> answer(InvocationOnMock arg0) throws Throwable {
Map<String, Object> headers = new HashMap<String, Object>();
HeaderInfo headerInfo = new HeaderInfo();
headers.put(BusinessServiceConstants.SERVICE_HEADER, headerInfo);
return headers;
}
});
}
#SuppressWarnings("deprecation")
#Test
public void testMethod() throws Exception {
SpecialFormMsgRequest arg = new SpecialFormMsgRequest();
Map<String, Object> headers = new HashMap<String, Object>();
Mockito.when(docMgmtServiceGateway.specialFormMsg(Mockito.any(SpecialFormMsgRequest.class),
(Matchers.<Map<String, Object>>any()))).thenReturn(new SendComnMsgResponse());
SpecialFormMsgRequest msg = new SpecialFormMsgRequest();
msg.setUiStaticDocFlag("N");
mvc.perform(post("/specialMsg").accept(MediaType.APPLICATION_JSON).content(asJsonString(msg))
.contentType(MediaType.APPLICATION_JSON)).andDo(print()).andExpect(status().isOk());
}
public static String asJsonString(final Object obj) {
try {
return new ObjectMapper().writeValueAsString(obj);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
Controller:
#Controller
public class DocMgmtImpl implements DocMgmt {
#Autowired
**DocMgmtService docMgmtServiceGateway;** **// I want to mock this service.**
#Override
#RequestMapping(value = "/specialMsg", method = RequestMethod.POST)
#ResponseBody
public SendComnMsgResponse specialMsg(#Valid #RequestBody final SpecialFormMsgRequest specialFormMsgRequest)
throws BusinessException, TechnicalException {
SendComnMsgResponse sendComnMsgResponse = null;
try {
Map<String, Object> headers = HeaderUtils.getHeaders(poBusinessHeader); // PowerMockito working here...
sendComnMsgResponse = **this.docMgmtServiceGateway.specialFormMsg(specialFormMsgRequest, headers);** // docMgmtServiceGateway is getting null...
} catch (Exception exception) {
handleException(exception);
}
return sendComnMsgResponse;
}
}
Gateway.xml:
<int:gateway id="docMgmtServiceGateway" service-interface="group.doc.svc.gateway.DocMgmtService"
default-reply-channel="docReplyChannel" error-channel="docErrorChannel">
<int:method name="sendComnMsg" request-channel="sendComnMsgRequestChannel" />
</int:gateway>
si-chain.xml:
<int:chain input-channel="esDBBISendComnMsgRequestChannel" output-channel="docReplyChannel">
<int:transformer method="formatRequest" ref="esSendComnMsgTransformer"/>
<int:service-activator ref="sendComnMsgActivator" method="sendComnMsg" />
<int:transformer method="parseResponse" ref="esSendComnMsgTransformer"/>
</int:chain>
I am wondering, whether I am doing correct or not. Because DocMgmtService service is an interface and it don't have implementation. After controller call goes to Transformer as configured above. On this setup I have following quetions.
Can I mock DocMgmtService service with same setup if not what will be correct approach.
If yes then how can I mock my service.
Thanks

It depends on exactly what you want to test.
If you mock the interface, all you are testing is your mock stubbing for that interface (pointless).
The framework creates an implementation of the interface which creates a message from the parameters and sends it to the channel.
You should auto wire the gateway into your test and call it.
You can mock any of the downstream components (e.g. sendComnMsgActivator) as needed.

Related

Mock not initiated on Static method

I am facing issues in mocking static method.
Below is my code where I am calling a static method
public class GetAllBatches {
public HttpResponseMessage run(
#HttpTrigger(route = "v1/batches",
name = "request",
methods = {HttpMethod.GET},
authLevel = AuthorizationLevel.ANONYMOUS)
HttpRequestMessage<String> request,
final ExecutionContext context){
context.getLogger().info("List batches Called");
String apiResponse ;
String connector = request.getQueryParameters().getOrDefault("connector", "");
try{
BatchesController batchesController = BatchesController.getInstance();
apiResponse = new Gson().toJson(batchesController.getBatches(connector));
}
}
}
BatchesController Class :
public class BatchesController {
Logger log = Logger.getLogger(BatchesController.class.getName());
public static BatchesController getInstance() {
if (batchesController == null) {
batchesController = new BatchesController(BatchDaoFactory.getDao());
}
return batchesController;
}
private static BatchesController batchesController = new BatchesController();
private final BatchDao batchDao;
public BatchesController(BatchDao BatchDao) {
this.batchDao = BatchDao;
}
// Do something
}
And below is the test that I have :
#RunWith(MockitoJUnitRunner.class)
public class GetAllBatchesTest {
#Mock
ExecutionContext context;
#Mock
HttpRequestMessage<String> request;
#Mock
BatchesController batchesController;
#Mock
BatchDao BatchDao;
#InjectMocks
GetAllBatches getAllBatchesMock = new GetAllBatches();
#Before
public void setUp() {
Map<String, String> map = new HashMap<>();
map.put("connector", "");
doReturn(Logger.getGlobal()).when(context).getLogger();
doReturn(map).when(request).getQueryParameters();
try (MockedStatic<BatchesController> utilities = Mockito.mockStatic(BatchesController.class)) {
utilities.when(BatchesController::getInstance).thenReturn(batchesController);
}
doAnswer((Answer<HttpResponseMessage.Builder>) invocationOnMock -> {
HttpStatus status = (HttpStatus) invocationOnMock.getArguments()[0];
return new HttpResponseMessageMock.HttpResponseMessageBuilderMock().status(status);
}).when(request).createResponseBuilder(any(HttpStatus.class));
}
#Test
public void testHttpTriggerJava() {
final HttpResponseMessage ret = getAllBatchesMock.run(request, context);
Assertions.assertEquals(ret.getStatus(), HttpStatus.OK);
}
When I run my test, it throws an error message :
java.lang.ExceptionInInitializerError
BatchesController.getInstance() is not actually returning the mock value.
I am not sure what is going wrong here ?
UPDATE :
I found out that the problem is because I am using Mockito-inline Mockito-inline fails to initiate mock on class but initiates mock only on interfaces
You are using a try-with-resources block to setup a static mock:
try (MockedStatic<BatchesController> utilities = Mockito.mockStatic(BatchesController.class)) {
utilities.when(BatchesController::getInstance).thenReturn(batchesController);
}
Remember that the static mock is only active in scope of the block - after you exit the block the resource is closed.
Thus, you need to:
move the static mock initialization from setup method to the test method
run code under test within the try-with-resources block

Mocking of new object and injecting it

I want to write junit for below method
public class ManageProfile{
public ResponseDTO create(SessionContext context, String flowId, Map<String, String> params) {
ApiClient apiClient=new ApiClient();
apiClient.setBasePath("ip");
Service service=new Service();
service.setApiClient(apiClient);
ResponseDTO response= service.createProfile(new RequestDto());
return response;
}
}
Its not spring based application.
class Test
#Test
public void testCreate() {
SessionContext sessionContext = mock(SessionContext.class);
ManageProfile manageProfile=new ManageProfile();
Service service=mock(Service.class);
when(service.createProfile(any())).thenReturn(new ResponseDTO());
String flowId = "1";
Map<String, String> params = new HashMap<>();
ResponseDTO responseDTO=manageProfile.create(sessionContext,flowId,params);
Assert.assertEquals("123"responseDTO.getId);
}
}
I am not able to inject mock Service object in ManageProfile as it is getting created using new keyword
Use spy to mock some methods in ManageProfile class
public class ManageProfile{
public ResponseDTO create(SessionContext context, String flowId, Map<String, String> params) {
ApiClient apiClient=new ApiClient();
apiClient.setBasePath("ip");
Service service = createService();
...
}
public Service createService(){
return new Service();
}
class Test {
#Test
public void testCreate() {
SessionContext sessionContext = mock(SessionContext.class);
ManageProfile manageProfile= spy(new ManageProfile());
Service service=mock(Service.class);
when(mangaeProfile.createService()).thenReturn(service);
...
}

how to mock restTemplate getForObject

I want to test the restTemplate.getForObject method using a mock but having issues. I'm new with Mockito, so I read some blogs about testing restTemplate using Mockito but still can not write a successful test.
The class to test is :
package rest;
#PropertySource("classpath:application.properties")
#Service
public class RestClient {
private String user;
// from application properties
private String password;
private RestTemplate restTemplate;
public Client getClient(final short cd) {
restTemplate.getInterceptors().add(new BasicAuthenticationInterceptor(user, password));
Client client = null;
try {
client = restTemplate.getForObject("http://localhost:8080/clients/findClient?cd={cd}",
Client.class, cd);
} catch (RestClientException e) {
println(e);
}
return client;
}
public RestTemplate getRestTemplate() {
return restTemplate;
}
public void setRestTemplate(final RestTemplate restTemplate) {
this.restTemplate = restTemplate;
}
}
My test class :
package test;
#PropertySource("classpath:application.properties")
#RunWith(MockitoJUnitRunner.class)
public class BatchRestClientTest {
#Mock
private RestTemplate restTemplate;
#InjectMocks
private RestClient restClient;
private MockRestServiceServer mockServer;
#Before
public void setUp() throws Exception {
}
#After
public void tearDown() throws Exception {
}
#Test
public void getCraProcessTest() {
Client client=new Client();
client.setId((long) 1);
client.setCd((short) 2);
client.setName("aaa");
Mockito
.when(restTemplate.getForObject("http://localhost:8080/clients/findClient?cd={cd},
Client.class, 2))
.thenReturn(client);
Client client2= restClient.getClient((short)2);
assertEquals(client, client2);
}
public RestTemplate getRestTemplate() {
return restTemplate;
}
public void setRestTemplate(RestTemplate restTemplate) {
this.restTemplate = restTemplate;
}
public RestClient getRestClient() {
return restClient;
}
public void setRestClient(RestClient restClient) {
this.restClient = restClient;
}
}
It is returning null and not the expected client, the restTemplate for Object class works fine. I want just to write the test . Am I missing something or doing the test wrong way?
Thanks for any guidance.
Use this instead:
Mockito.when(restTemplate.getForObject(
"http://localhost:8080/clients/findClient?cd={id}",
Client.class,
new Object[] {(short)2})
).thenReturn(client);
The third parameter is a varargs.
So you need to wrap into an Object[] in the test, otherwise Mockito is not able to match it. Note that this happens automatically in your implementation.
Also:
You forgot to terminate your url (missing closing ") in your examples in the question. Probably just a typo.
You used different url's in your implementation in your test: ...?cd={cd} instead of ...?cd={id}.(As previously pointed out by #ArnaudClaudel in the comments).
You did not define a behaviour for restTemplate.getInterceptors() so I would expect it to fail with a NullPointerException, when trying to add the BasicAuthenticationInterceptor.
Additionally you might want to check my answer here for another example of how to mock the getForObject method. Note that it does not include a case where any of the real parameters would be null.

Spring Boot with xml and json with jackson only returns xml

Let me thank you in advance for your help!
I have a weird behaviour in an spring boot application. Let me explain it for you:
I'm wrapping some legacy web services (custom xml messages) with some nice rest-json services (via spring-mvc and spring boot and using jackson for serializing stuff)
In order to communicate with the legacy systems, I have created a custom XmlMapper, serializers and deserializers.
And finally, I have created an httpclientconfig, in order to define some http connection properties...
But after starting the app and trying to visit any endpoint (actuator ones for example), the app only returns xml. Event swagger endpoints return xml (what makes swagger-ui going nuts.
These are some of the classes:
#Configuration
public class HttpClientConfig {
private static final Logger logger = LoggerFactory.getLogger(HttpClientConfig.class);
#Value(value = "${app.http.client.max_total_connections}")
public String MAX_TOTAL_CONNECTIONS;
#Value(value = "${app.http.client.max_connections_per_route}")
public String MAX_CONNECTIONS_PER_ROUTE;
#Value(value = "${app.http.client.connection_timeout_milliseconds}")
public String CONNECTION_TIMEOUT_MILLISECONDS;
#Bean
public ClientHttpRequestFactory httpRequestFactory() {
return new HttpComponentsClientHttpRequestFactory(httpClient());
}
#Autowired
private XmlMapper xmlMapper;
#Bean
public RestTemplate restTemplate() {
RestTemplate restTemplate = new RestTemplate(httpRequestFactory());
List<HttpMessageConverter<?>> converters = restTemplate.getMessageConverters();
for (HttpMessageConverter<?> converter : converters) {
if (converter instanceof MappingJackson2HttpMessageConverter) {
MappingJackson2HttpMessageConverter jsonConverter = (MappingJackson2HttpMessageConverter) converter;
jsonConverter.setObjectMapper(new ObjectMapper());
}
if (converter instanceof MappingJackson2XmlHttpMessageConverter) {
MappingJackson2XmlHttpMessageConverter jsonConverter = (MappingJackson2XmlHttpMessageConverter) converter;
jsonConverter.setObjectMapper(xmlMapper);
}
}
logger.debug("restTemplate object created====================================");
return restTemplate;
}
#Bean
public HttpClient httpClient() {
HttpClient httpClient = null;
try {
HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
// disable SSL check
SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
#Override
public boolean isTrusted(java.security.cert.X509Certificate[] arg0, String arg1)
throws CertificateException {
return true;
}
}).build();
httpClientBuilder.setSSLContext(sslContext);
// don't check Hostnames
HostnameVerifier hostnameVerifier = NoopHostnameVerifier.INSTANCE;
SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.getSocketFactory())
.register("https", sslSocketFactory).build();
PoolingHttpClientConnectionManager connMgr = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
connMgr.setMaxTotal(Integer.parseInt(MAX_TOTAL_CONNECTIONS));
connMgr.setDefaultMaxPerRoute(Integer.parseInt(MAX_CONNECTIONS_PER_ROUTE));
RequestConfig config = RequestConfig.custom()
.setConnectTimeout(Integer.parseInt(CONNECTION_TIMEOUT_MILLISECONDS)).build();
httpClientBuilder.setDefaultRequestConfig(config);
httpClientBuilder.setConnectionManager(connMgr);
// to avoid nohttpresponse
httpClientBuilder.setRetryHandler(new HttpRequestRetryHandler() {
#Override
public boolean retryRequest(IOException exception, int executionCount,
org.apache.http.protocol.HttpContext context) {
// TODO Auto-generated method stub
return true;
}
});
httpClient = httpClientBuilder.build();
} catch (Exception e) {
logger.error("Excption creating HttpClient: ", e);
}
return httpClient;
}
}
And the xml mapper
#Configuration
public class XmlMapperConfig{
#Bean
public XmlMapper getXmlMapper() {
XmlMapper mapper=new XmlMapper();
SimpleModule module = new SimpleModule();
module.addSerializer(CafRequestObject.class, new CafRequestObjectSerializer());
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
mapper.registerModule(module);
mapper.findAndRegisterModules();
CafXmlSerializationProvider cafXmlProvider=new CafXmlSerializationProvider(new XmlRootNameLookup());
mapper.setSerializerProvider(cafXmlProvider);
return mapper;
}
}
I call to findAndregisterModules, because I am also developing some libraries which provides additional serializers for services (modularized stuff)
I'm completely lost with this. Any help would be much appreciated...
Regards!
I have solved it extending WebMvcConfigurerAdapter:
#Configuration
#EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
#Override
public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
configurer.defaultContentType(MediaType.APPLICATION_JSON);
}
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry
.addResourceHandler("swagger-ui.html")
.addResourceLocations("classpath:/META-INF/resources/");
registry
.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/");
}
}
Thanks again!

Junit for Controller class

I have controller method and for it I am making Junit but getting Null pointer error when it calling a service method. I used power mock but still getting Null pointer.
method:
#RequestMapping(method = RequestMethod.GET, value = "/DSR.do")
public ModelAndView displayDataSourceReportPage(HttpServletRequest request,Model model) {
log.debug(" Inside displayDataSourceReportPage method ");
Map<String, Object> map = new HashMap<String, Object>();
try {
request.setAttribute(MENU_SELECTED, LABEL_MENU_SOURCEDATA);
request.setAttribute(SUB_MENU_SELECTED, LABEL_SUBMENU_DSR);
#SuppressWarnings("rawtypes")
List dataSource = dataSourceReportService.listDataSourceReportByCurrentRunInd("C");
map.put("dataSource", dataSource);
} catch (Exception e) {
log.error(e.getMessage(), e);
}
return new ModelAndView("DataSourceReport", "model", map);
}
test Method:
#InjectMocks
private DataSourceReportController dataSourceReportController;
#Mock
private DataSourceReportService dataSourceReportServiceImpl;
#InjectMocks
private DataSourceReportDAO dataSourceReportDAO = new DataSourceReportDAOImpl();
#Before
public void setup() {
MockitoAnnotations.initMocks(this);
}
#Test
public void testdisplayDataSourceReportPage() throws Exception {
PowerMockito.mockStatic(DataSourceReport.class);
PowerMockito.mockStatic(HttpServletRequest.class);
PowerMockito.mockStatic(Model.class);
PowerMockito.mockStatic(DataSourceReportService.class);
HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
Model model = Mockito.mock(Model.class);
dataSourceReportServiceImpl = PowerMockito.mock(DataSourceReportService.class);
DataSourceReport dataSourceReport = PowerMockito.mock(DataSourceReport.class);
dataSourceReport.setCurrentRunInd("abc");
dataSourceReport.setActualFileName("Somthing");
dataSourceReport.setFileCountId(3);
dataSourceReport.setFileId(4);
dataSourceReport.setRecCount(3);
List<DataSourceReport> list = new ArrayList<DataSourceReport>();
list.add(dataSourceReport);
String currentRunInd = "currentRunInd";
Object obj =getClass();
PowerMockito.when(dataSourceReportDAO.listDataSourceReportByCurrentRunInd(currentRunInd)).thenReturn(list);
DataSourceReportController ctrl = new DataSourceReportController();
ctrl.displayDataSourceReportPage(request, model);
}
getting Null at "dataSourceReportService.listDataSourceReportByCurrentRunInd("C");"
You need to have this in the test class
PowerMockito.when(dataSourceReportService.listDataSourceReportByCurrentRunInd("C")).thenReturn(list);
before calling
ctrl.displayDataSourceReportPage(request, model);
Thanks # Arthur Zagretdinov
I tried the below code and it worked.
private MockMvc mockMvc;
#Mock
private HttpServletRequest req;
#Mock
private DataSourceReportService dataSourceReportServiceImpl;
#InjectMocks
private DataSourceReportController controller;
#Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
mockMvc = MockMvcBuilders.standaloneSetup(controller).build();
}
#Before
public void initMocks(){
MockitoAnnotations.initMocks(this);
}
#Test
public void testdisplayDataSourceReportPage() throws Exception {
HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
Model model = Mockito.mock(Model.class);
DataSourceReport dataSourceReport =Mockito.mock(DataSourceReport.class);;
dataSourceReport.setCurrentRunInd("abc");
dataSourceReport.setActualFileName("Somthing");
dataSourceReport.setFileCountId(3);
dataSourceReport.setFileId(4);
dataSourceReport.setRecCount(3);
List<DataSourceReport> list = new ArrayList<DataSourceReport>();
list.add(dataSourceReport);
ModelAndView modelView = controller.displayDataSourceReportPage(request, model);
modelView.addObject(dataSourceReport);
}