0

I have started newly working on testing using mockito. I have 2 questions ...

1. Question

I have method like below with optional and must have parameter so when I call this service method without the must params it should throw Exception.

@RequestMapping( method=RequestMethod.GET, produces={"application/xml", "application/json"})
    public ResponseEntity<PResponse> get(@RequestParam(value="params1",required=false) String params1,
        @RequestParam(value ="params2",required=false) String params2,
        @RequestParam(value= "params3",required=true) String params3,
        @RequestParam(value="refresh",required=false) boolean refresh,
        @RequestParam(value="params4",required=true) List<String> params4)
    {method logic ...}

Here params1,2,refresh are optional and params3,4 are must so when i get request with out params3,4 it should give an error. I am trying to write a test for this using mockito

@Test(expected = RuntimeException.class)
public void throwExceptionIfMissingParams34() throws RuntimeException {
    when(myService.get(argThat(new MessagesArgumentMatcher()))).thenThrow(new RuntimeException()) ;
}

I am getting error saying get() in myService can't be applied to expected Parameters:, Actual Arguments:

2. Question :

In the above get method I am calling other method which calls other service method to get data from DB

List<Product> lstProduct = productComponent.readProduct(params3,params4);

which calls

Product product = productReader.readProduct(params3, params4, Product.class); 

where in ProductReader.java Service class it gets data from DB by running query. I am trying to test the

List lstProduct = productComponent.readProduct(params3,params4); in get() method so I tried mocking the Service Object but getting NullPointer Exception when I run the test.

Community
  • 1
  • 1
user1653027
  • 789
  • 1
  • 16
  • 38

1 Answers1

0

Ad 1. Question

@RequestParam is an annotation from Spring Framework. It's used to define parameters for Controllers. The annotation is used by Spring to map the web request params to arguments which your controller accepts. Testing this behaviour would be actually testing Spring itself. I wouldn't do that. Another thing is, are you really testing a Service, or rather a Controller?

Besides, Java doesn't have the possibility to invoke a method with different arguments than defined, the only possibility is to use varargs.

Ad. Question 2

You didn't specify form where you are getting the NPE. But a first guess would be that you didn't configure Mockito correctly. For example take a look at: NullPointerException in mockito unit test

Community
  • 1
  • 1
gmaslowski
  • 774
  • 5
  • 13
  • thanks for the information, Question1. yes i didn't know that point. got it now. Question2. There was a mistake while mocking the productComponent fixed the nullpointerException – user1653027 Jun 14 '16 at 05:00