I am trying to mock the external call.
ResponseEntity<?> httpResponse = requestGateway.pushNotification(xtifyRequest);
requestGateway is an interface.
public interface RequestGateway
{
ResponseEntity<?> pushNotification(XtifyRequest xtifyRequest);
}
Below is the test method i am trying to do.
#Test
public void test()
{
ResponseEntity<?> r=new ResponseEntity<>(HttpStatus.ACCEPTED);
when(requestGateway.pushNotification(any(XtifyRequest.class))).thenReturn(r);
}
A compilation error is there in the above when statement,saying it as an invalid type.even thougg r is of type ResponseEntity.
Can anyone please help me to solve this issue ?
You can instead use the type-unsafe method
doReturn(r).when(requestGateway.pushNotification(any(XtifyRequest.class)));
Or you can remove the type info while mocking
ResponseEntity r=new ResponseEntity(HttpStatus.ACCEPTED);
when(requestGateway.pushNotification(any(XtifyRequest.class))).thenReturn(r);
Related
I need to mock the following Model Mapper Strict strategy configuration with the mockito.
modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT);
I tried the following in my test method but i am getting Null Pointer Exception.
#Test
public void mockModelMapper(){
when(modelmapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT))
.thenReturn(modelmapper.getConfiguration());
}
Thanks in advance.
As mentioned by #DCTID, you can't chain the mocks. You need to split each method call and inject a mock for the object returned by getConfiguration().
#Test
public void mockModelMapper(){
// Inject the configuration mock
Configuration configurationMock = mock(Configuration.class);
when(configurationMock.setMatchingStrategy(MatchingStragegies.STRICT)
.thenReturn(configuraitonMock);
when(modelmapper.getConfiguration()).thenReturn(configurationMock);
}
I've integrated Katharsis with spring-boot (MVC + Security) and I'm realy happy about it.
#SpringBootApplication
#Import(KatharsisConfigV2.class)
#Configuration
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
I began to setup security with an extra spring mvc controller to handle login and logout methods.
But with a RequestBody annotated parameters to convert json to java object, I've got a 400 response telling me required body is missing.
#RequestMapping(value = "/auth/signup", method = RequestMethod.POST)
public #ResponseBody AuthenticationResponse signup(
#RequestBody AuthenticationRequest authenticationRequest) {
...
}
When I remove the import for Katharsis configuration, everything goes fine.
#SpringBootApplication
//#Import(KatharsisConfigV2.class)
#Configuration
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
How could I tweak my project configuration to allow basics spring controllers to accept standard JSON?
Thanks in advance
What is the exact message in the "detail" field of the response? Katharsis-Spring provides decent error details. That should provide you a better idea of exactly what's wrong.
Remember that POST bodies in JSON API will differ from how they look in regular Spring, e.g. there needs to be a "data" field in your payload.
You may also need to configure Katharsis in your application.properties file. Katharsis can't process requests unless it's configured properly.
Hope this helps.
I have Dropwizard application and I am writing unit tests for it. I am following Dropwizard's documentation to do so : http://dropwizard.readthedocs.org/en/latest/manual/testing.html
What I am missing is how can I add parameter to my test which invokes GET method?
Here in the documentation :
assertThat(resources.client().resource("/person/blah").get(Person.class))
.isEqualTo(person);
What if my get method has a parameter?
In Jersey's WebResource there are:
#Override
public <T> T get(Class<T> c) throws UniformInterfaceException, ClientHandlerException {
return handle(c, build("GET"));
}
#Override
public <T> T get(GenericType<T> gt) throws UniformInterfaceException, ClientHandlerException {
return handle(gt, build("GET"));
}
Query parameters are part of the resource URI. You can embed them in the string:
assertThat(resources.client().resource("/person/blah?a=b").get(Person.class)).isEqualTo(person);
Or you can build the URI dynamically:
URI resourceUri = UriBuilder.fromPath("/person/blah").queryParam("a", "b").build();
assertThat(resources.client().resource(resourceUri).get(Person.class)).isEqualTo(person);
I use Jersey and I have the following Rest function which returns a JSON string when my server is deployed:
#GET
#Path("getallemployees")
#Produces("application/json")
public Response getAllEmployees() {
//building the entity object which is List<Employee>
return Response.ok(entity).build();
}
I need to develop some unit tests (not integration testing) and I want to somehow mock the HTTPRequest that invokes this method and then get the json String. The best option would be to use mockito for this.
Is there any suggestion on how to do it ?
Thanks !!
The problem is that the method returns a Response object to the caller which is deep within the framework code. It doesn't return JSON strings.
You can use Mockito, if you need to mock something inside the method itself. That should work.
But you may need to take the value returned by the method and convert it to JSON like this if you are using Jackson with Jersey.
Response response = getAllEmployees();
Object retval = response.getEntity();
try {
ObjectMapper mapper = new ObjectMapper();
// I like this formatting. You can change it.
mapper.configure(Feature.INDENT_OUTPUT, true);
mapper.configure(Feature.WRITE_ENUMS_USING_TO_STRING, true);
mapper.configure(Feature.USE_ANNOTATIONS, false);
mapper.configure(Feature.FAIL_ON_EMPTY_BEANS, false);
mapper.setSerializationInclusion(Inclusion.NON_NULL);
mapper.getSerializationConfig().setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL);
mapper.getSerializationConfig().withSerializationInclusion(JsonSerialize.Inclusion.NON_NULL);
String json = mapper.writeValueAsString(retval);
... assert something about the string
} catch (JsonProcessingException e) {
// do something
} catch (IOException e) {
// do something
}
Some of this is guess work and speculation on my part but it may help. You could try using the Jersey Test Framework with the InMemoryTestContainerFactory:
It starts Jersey application and directly calls internal APIs to handle request created by client provided by test framework. There is no network communication involved. This containers does not support servlet and other container dependent features, but it is a perfect choice for simple unit tests.
It looks like to use it, all you need to do is extend JerseyTest and then override getTestContainerFactory() and follow the rest of the instructions, e.g.:
public class EmployeeResourceTest extends JerseyTest {
#Override
protected Application configure() {
// set up employee resource with mock dependencies etc...
return new ResourceConfig().registerInstances(employeeResource);
}
#Test
public void getAllEmployees() {
final String response = target("getallemployees").request().get(String.class);
// assert etc...
}
}
I used registerInstances instead of registerClasses in configure() as it looks like you can present a ready made Resource but set up with any mock dependencies you may want - although I haven't tried this myself.
The test class is a bit inflexible as you can only do one-time set up of dependencies in the configure() method, so it might be worth investigating using the MockitoJUnitRunner - although I'm not sure if it will work with the JerseyTest inheritance. It could allow you to do add behaviour to mocks in each #Test method, e.g.:
#Mock
private EmployeeResourceDependency dependency;
#InjectMocks
private EmployeeResource employeeResource;
// configure() as above but without mock setup up etc...
#Test
public void getAllEmployees() {
given(dependency.getEmployees()).willReturn(...);
// etc...
But like I said it might not be possible to mix them at all.
I'm attempting to bind json to the model with #RequestBody.
We are validating our model using JSR303.
Here is the method signature
#RequestMapping(value = "/editCampaign.do", method = { RequestMethod.POST })
public ModelAndView editCampaign(#RequestBody #Valid Campaign campaign,
HttpServletRequest request)
If a piece of required information is missing a MethodArgumentNotValidException is thrown (as I read in the docs). I really want to be able to return this information back to the view so I can show the user that they've not filled out a required field. Once the exception is thrown, it seems as though it's too late. Obviously, I don't have a bindingresult to inspect.
Am I incorrectly using the framework? How do I set up this scenario correctly?
First Of all I recommend you to return String instead ModelAndView especially in Spring 3.1.
If you want to catch Exception from #ResponseBody annotated method, I recommend you to use the following:
1) Catch the exception with #ExceptionHandler annotation:
#ExceptionHandler(MethodArgumentNotValidException.class)
public String handleMyException(MethodArgumentNotValidException exception) {
return "redirect:errorMessage?error="+exception.getMessage());
}
and then Redirect to view annotated with #ResponseBody argument
#RequestMapping(value="/errorMessage", method=RequestMethod.GET)
#Responsebody
public String handleMyExceptionOnRedirect(#RequestParamter("error") String error) {
return error;
}