Testing Spring with MockMvc - java

please could help to me with Spring testing with MockMvc.
I have Controller(I deleted path code of metod)
#Controller
#RequestMapping("/read/object-attributes")
public class GroupAttributeReadController {
#Autowired
private GroupAttributeService groupAttributeService;
#RequestMapping(value = "/import", method = RequestMethod.GET)
public
#ResponseBody
GroupAttributeBufferListResponse findAll(#RequestParam(value = "pageNum", required = true) int pageNum,
#RequestParam(value = "pageSize", required = true) int pageSize,
#RequestParam(value = "order", required = false) String order,
#RequestParam(value = "orderDir", required = false) String orderDir,
#RequestParam(value = "loadSession") Long loadSession,
#RequestParam( value = "showCorrect", defaultValue = "0") Integer showCorrect,
#RequestParam(value="naviUser") String user,
#RequestParam Map<String, String > params,
HttpServletResponse response, Locale locale) {
}
And my test
#RunWith(SpringJUnit4ClassRunner.class)
#WebAppConfiguration
public class ControllersTest {
#Autowired
WebApplicationContext wac;
MockMvc mockMvc;
#Before
public void setup() {
DefaultMockMvcBuilder builder = MockMvcBuilders.webAppContextSetup(this.wac);
this.mockMvc = builder.build();
}
#Test
public void testController() throws Exception {
ResultMatcher ok = MockMvcResultMatchers.status().isOk();
MockHttpServletRequestBuilder request = MockMvcRequestBuilders.get("/read/object-attributes/import?pageNum=2&pageSize=5&order=test&orderDir=DESC&loadSession=1&showCorrect=0&naviUser=user&FILTER_Test=Test");
this.mockMvc.perform(request)
.andExpect(ok);
}
}
But I'm not understand why response 404. Maybe I something forget? Maybe need config-file, I dont know :(
java.lang.AssertionError: Status
Expected :200
Actual :404
<Click to see difference>
at org.springframework.test.util.AssertionErrors.fail(AssertionErrors.java:54)
at org.springframework.test.util.AssertionErrors.assertEquals(AssertionErrors.java:81)
at org.springframework.test.web.servlet.result.StatusResultMatchers$10.match(StatusResultMatchers.java:665)
at org.springframework.test.web.servlet.MockMvc$1.andExpect(MockMvc.java:171)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
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.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:252)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:51)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)

You need to provide the required params.
Example:
#Test
public void testAddInformation() throws Exception {
this.mockMvc.perform(post("/sample").param("name", "provideName").param("address", "provideAddress")).andExpect(status().isOk());
};

You should include #ContextConfiguration as well - here is a snippet from #WebAppConfiguration documentation:
Note that #WebAppConfiguration must be used in conjunction with
#ContextConfiguration, either within a single test class or within a test class hierarchy.
So your test class should look something like that:
#RunWith(SpringJUnit4ClassRunner.class)
#WebAppConfiguration
#ContextConfiguration( classes = AppConfig.class, WebConfig.class )
public class ControllersTest {
(...)
}

Related

Spring-boot WebMvcTest, why am i getting this NullPointer when i provide a mocked UserDetailsService?

I am trying to create some #WebMvcTest cases in Spring boot. I have a controller under test and i am trying to use #WithUserDetails so that i can test the Authentication object that gets passed to my controller method as a parameter.
I have a custom UserDetails extension named EmployeeDetails.
I mock my UserDetailsService with #MockBean and i make it return a custom EmployeeDetails object using given(userDetailsService.loadUserByUsername(anyString())).willReturn(new EmployeeDetails(employee, account));
However, when i run the test i get the following error:
java.lang.IllegalStateException: Unable to create SecurityContext using #org.springframework.security.test.context.support.WithUserDetails(setupBefore=TEST_METHOD, userDetailsServiceBeanName=userDetailsService, value=someemail#email.com)
at org.springframework.security.test.context.support.WithSecurityContextTestExecutionListener.createTestSecurityContext(WithSecurityContextTestExecutionListener.java:126)
at org.springframework.security.test.context.support.WithSecurityContextTestExecutionListener.createTestSecurityContext(WithSecurityContextTestExecutionListener.java:96)
at org.springframework.security.test.context.support.WithSecurityContextTestExecutionListener.beforeTestMethod(WithSecurityContextTestExecutionListener.java:62)
at org.springframework.test.context.TestContextManager.beforeTestMethod(TestContextManager.java:289)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:74)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:251)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:230)
at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:58)
Caused by: java.lang.NullPointerException
at org.springframework.security.test.context.support.WithUserDetailsSecurityContextFactory.createSecurityContext(WithUserDetailsSecurityContextFactory.java:63)
at org.springframework.security.test.context.support.WithUserDetailsSecurityContextFactory.createSecurityContext(WithUserDetailsSecurityContextFactory.java:44)
at org.springframework.security.test.context.support.WithSecurityContextTestExecutionListener.createTestSecurityContext(WithSecurityContextTestExecutionListener.java:123)
... 23 more
What is causing this? I don't understand. I am under the impression that the mocked UserDetailsService should return the object that i provide in the given call. Why am i getting the NullPointer? Can anyone point me in the right direction?
Thanks!
This is my test case:
#RunWith(SpringRunner.class)
#WebMvcTest(PDPController.class)
#AutoConfigureMockMvc(addFilters = false)
public class PDPControllerTests {
#Autowired
private MockMvc mvc;
#Autowired
private ObjectMapper objectMapper;
#MockBean
private PDPService pdpService;
#MockBean(name = "userDetailsService")
private MyUserDetailsService userDetailsService;
//..
#Test
#WithUserDetails(value = "someemail#email.com", userDetailsServiceBeanName = "userDetailsService")
public void testSaveBackground_returns_result_from_service() throws Exception {
PersonalDevelopmentPlan pdp = new PersonalDevelopmentPlan();
pdp.setEmployee(EMPLOYEE_ID);
Account account = new Account();
Employee employee = new Employee();
given(pdpService.saveBackground(eq(EMPLOYEE_ID), any(), anyInt())).willReturn(pdp);
given(userDetailsService.loadUserByUsername(anyString())).willReturn(new EmployeeDetails(employee, account));
mvc.perform(patch(URL_WITH_ID + "/background").secure(true)
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(pdp)))
.andExpect(status().isOk())
.andExpect(jsonPath("$.employee", Matchers.is(EMPLOYEE_ID)));
}
}
Add the following
#PostConstruct
public void setup() {
Account account = new Account();
Employee employee = new Employee();
given(userDetailsService.loadUserByUsername(anyString()))
.willReturn(new EmployeeDetails(employee, account));
}
And remove the following line from inside the test method
given(userDetailsService.loadUserByUsername(anyString()))
.willReturn(new EmployeeDetails(employee, account));

JUnit AssertionError: Expecting code to raise a throwable

I am trying to write a test for a method that throws custom exception. It fails with Assertion error. What could be done to properly catch the exception and pass the test?
Service method:
#Service
public class CustomServiceImpl implements CustomService {
#Autowired
UserUtil userUtil;
public ResultDTO getResultDto (String type, Long id) throws CustomException {
User user = userUtil.getCurrentUser();
if (user == null) {
throw new CustomException("User does not exist");
}
}
}
Test method:
#MockBean
CustomServiceImpl customServiceImpl ;
#Test
public void test01_getResultDto() {
UserUtil userUtil = Mockito.mock(UserUtil.class);
Mockito.when(userUtil.getCurrentUser()).thenReturn(null);
Assertions.assertThatThrownBy(() -> customServiceImpl.getResultDto (Mockito.anyString(), Mockito.anyLong()))
.isInstanceOf(CustomException .class)
.hasMessage("User does not exist");
}
This test fails with the following error:
java.lang.AssertionError: Expecting code to raise a throwable.
at com.ps.service.CustomServiceImplTest.test01_getResultDto(CustomServiceImplTest.java:62)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
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.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:252)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:89)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:41)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:541)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:763)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:463)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:209)
--------------------------- EDIT ------------------------
Changed the code Test to include the following
#Mock
UserUtil userUtil;
#InjectMocks
CustomServiceImpl cutomServiceImpl;
#Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
}
#Test
public void test01_getResultDto() {
when(userUtil.getCurrentUser()).thenReturn(null);
assertThatThrownBy(() -> customServiceImpl.getResultDto ("type", 1L))
.isInstanceOf(CustomException .class)
.hasMessage("User does not exist");
}
Seems to be working.
Thanks to the advice in comments.
I have made suitable changes to my original code and the following set up works well.
#Mock
UserUtil userUtil;
#InjectMocks
CustomServiceImpl cutomServiceImpl;
#Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
}
#Test
public void test01_getResultDto() {
when(userUtil.getCurrentUser()).thenReturn(null);
assertThatThrownBy(() -> customServiceImpl.getResultDto ("type", 1L))
.isInstanceOf(CustomException .class)
.hasMessage("User does not exist");
}
Another way you can do it is :
#MockBean
CustomServiceImpl customServiceImpl ;
#Rule
public ExpectedException exceptionRule = ExpectedException.none();
#Test
public void test01_getResultDto() {
exceptionRule.expect(CustomException.class);
UserUtil userUtil = Mockito.mock(UserUtil.class);
Mockito.when(userUtil.getCurrentUser()).thenReturn(null);
customServiceImpl.getResultDto ("type", 1L);
}

java.lang.NullPointerException is occuring due to property is not loading in Mockito when mocking a method

I am new to Mockito and i am facing a issue due to a property is not loading in from appication.properties file.
Problem statement: I am trying to mock a method which uses a property from the application.properties file. When the control arrives at the line to load property value it shows null and because of this mockito throws java.lang.NullPointerException.
What i am looking for is how to load the property from application.properties file when mocking a method.
Here i am trying to load global variable partsListGlobal .Please help me how to achieve this.?
Here is my below code snippet.
#Service
public class ClimoDiagnosticReportServImpl implements ClimoDiagnosticReportService {
#Value("${PARTS_LIST}")
private String partsListGlobal;
#Override
public boolean getSomeResult() {
String[] partsListLocal = getPartsList();
List<String> partsList = Arrays.asList(partsListGlobal);
if (partsList.contains("PART_X1"))
return true;
else
return false;
}
public String[] getPartsList() {
return partsListGlobal.split(",");// Here is the error occuring due to partsListGlobal is not loading the value from application.properties file.
}
}
#RunWith(MockitoJUnitRunner.class)
public class ClimoDiagnosticReportServImplTest {
#InjectMocks
private ClimoDiagnosticReportServImpl serviceReference1;
#Mock
private ClimoDiagnosticReportServImpl serviceReference12;
#Before
public void setup() {
MockitoAnnotations.initMocks(this);
}
#Test
public void getSomeResultTest() {
boolean result1 = false;
String[] strArray = new String[2];
strArray[0] = "P1";
strArray[1] = "P2";
Mockito.when(serviceReference12.getPartsList()).thenReturn(strArray);
boolean result2 = serviceReference1.getSomeResult();
Assert.assertEquals(result1,result2);
}
}
Error:
java.lang.NullPointerException at
com.test.serviceimpl.ClimoDiagnosticReportServImpl.getPartsList(ClimoDiagnosticReportServImpl.java:68)
at
com.test.serviceimpl.ClimoDiagnosticReportServImpl.getSomeResult(ClimoDiagnosticReportServImpl.java:57)
at
com.test.serviceimpl.ClimoDiagnosticReportServImplTest.getSomeResultTest(ClimoDiagnosticReportServImplTest.java:74)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498) 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.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325) at
org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at
org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) at
org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) at
org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) at
org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) at
org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) at
org.junit.runners.ParentRunner.run(ParentRunner.java:363) at
org.mockito.internal.runners.JUnit45AndHigherRunnerImpl.run(JUnit45AndHigherRunnerImpl.java:37)
at
org.mockito.runners.MockitoJUnitRunner.run(MockitoJUnitRunner.java:62)
at
org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
at
org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at
org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
at
org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:678)
at
org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at
org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
Thanks everyone in advance.
You don't have any dependency to mock in the service. Mockito is thus completely unnecessary. What you need to do is to set the private String field, that is populated by Spring in your application using reflection.
Just follow the best practice os using cnstructor injection instead of field injection, and that will make your code testable (that's one of the reasons why it's a best practice):
#Service
public class ClimoDiagnosticReportServImpl implements ClimoDiagnosticReportService {
private String partsListGlobal;
public ClimoDiagnosticReportServImpl(#Value("${PARTS_LIST}") String partsListGlobal) {
this.partsListGlobal = partsListGlobal;
}
// ...
}
Your test now can be reduced to
public class ClimoDiagnosticReportServImplTest {
#Test
public void shouldReturnTrueIfPropertyContainsPartX1() {
ClimoDiagnosticReportServImpl service = new ClimoDiagnosticReportServImpl("a,b,c,PART_X1,d");
assertTrue(service.getSomeResult());
}
#Test
public void shouldReturnFalseIfPropertyDoesNotContainPartX1() {
ClimoDiagnosticReportServImpl service = new ClimoDiagnosticReportServImpl("a,b,c,d");
assertFalse(service.getSomeResult());
}
}

ModelMapper JUnit Mockito throws NullPointerException

I'm trying to test a method in service class which uses ModelMapper to convert entity to dto, but I'm getting NullPointerException at this line mapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT); in the service class.
Exception
java.lang.NullPointerException
at pro.budthapa.service.impl.StockCategoryServiceImpl.getStockCategoryByIdAndBusinessGroupId(StockCategoryServiceImpl.java:56)
at pro.budthapa.service.impl.StockCategoryServiceImplTest.WhenCategoryPresent_ShouldReturnCategory(StockCategoryServiceImplTest.java:81)
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.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.mockito.internal.runners.JUnit45AndHigherRunnerImpl.run(JUnit45AndHigherRunnerImpl.java:37)
at org.mockito.runners.MockitoJUnitRunner.run(MockitoJUnitRunner.java:62)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:538)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:760)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:460)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:206)
Test Class
#RunWith(MockitoJUnitRunner.class)
public class StockCategoryServiceImplTest {
#Mock
private ModelMapper mapper;
#Mock
private StockCategoryRepository stockCategoryRepository;
#InjectMocks
private StockCategoryServiceImpl stockCategoryService;
#Before
public void setup() {
mapper = new ModelMapper();
}
#Test
public void WhenCategoryPresent_ShouldReturnCategory() throws Exception {
int bgId = 10;
int categoryId = 5;
StockCategory sc = new StockCategory();
sc.setCategoryId(categoryId);
sc.setBusinessGroupId(String.valueOf(bgId));
sc.setDescription("Test Item");
Mockito.when(stockCategoryRepository.findByCategoryIdAndBusinessGroupId(categoryId, String.valueOf(bgId))).thenReturn(Optional.of(sc));
StockCategoryDto result = stockCategoryService.getStockCategoryByIdAndBusinessGroupId(categoryId, bgId);
assertEquals(5, result.getCategoryId() );
assertEquals(10, result.getBusinessGroupId());
assertNotNull(result.getDescription());
Mockito.verify(stockCategoryRepository, Mockito.times(1)).findByCategoryIdAndBusinessGroupId(categoryId, String.valueOf(bgId));
}
}
Service Class
#Service
public class StockCategoryServiceImpl implements StockCategoryService {
private ModelMapper mapper;
private StockCategoryRepository stockCategoryRepository;
public StockCategoryServiceImpl(ModelMapper mapper, StockCategoryRepository stockCategoryRepository) {
this.mapper = mapper;
this.stockCategoryRepository = stockCategoryRepository;
}
#Override
public StockCategoryDto getStockCategoryByIdAndBusinessGroupId(int categoryId, int bgId) {
Optional<StockCategory> cat = stockCategoryRepository.findByCategoryIdAndBusinessGroupId(categoryId, String.valueOf(bgId));
if(cat.isPresent()) {
//getting NullPointerException at this line
mapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT);
return mapper.map(cat.get(), StockCategoryDto.class);
}
StockCategoryDto dto = new StockCategoryDto();
dto.setMessage("Category not found for given id: "+categoryId);
return dto;
}
}
You shouldn't reassign your mocked ModelMapper in setup method. Remove this method
And I can't find in your code mock definition for mapper.getConfiguration()
when(mapper.getConfiguration()).thenReturn(...)
You should tell it to mockito.

Null Pointer Exception, when Writing Junit/Mockito Test cases at Controller class for Oauth, JSON response

I'm relatively new to Testing in Mockito, and I'm trying to write few test cases for Controller level testing and I'm getting Null pointer Exception when I'm running the test case. I'm Injecting mocks at controller layer and mocking the service layer methods. Please let me know, the issue
Controller Class:
#RestController
#RequestMapping(value="v1.0/authentication")
public class OauthTokenController {
//Logging
private static final Logger LOG = LoggerFactory.getLogger(OauthTokenController.class);
#Autowired
private SsasServiceImpl ssasService;
#RequestMapping(value="/oauth/token", method=RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
public TokenActivationResponse grantToken(#RequestParam("username") String username, #RequestParam("password") String password, #RequestParam("grant_type") String grant_type){
TokenActivationResponse tokenActivationResponse = new TokenActivationResponse();
SecureString passwordSecured = new SecureString(password);
try{
tokenActivationResponse = ssasService.grantToken(username, passwordSecured, grant_type);
if(tokenActivationResponse == null){
throw new Exception();
}
LOG.info("Printing the response " + tokenActivationResponse);
}catch(Exception e){
LOG.error("Exception in oauth token granting controller", e);
}
return tokenActivationResponse;
}
}
SSASServiceImpl:
public class SSASServiceImpl{
public TokenActivationResponse grantToken(String username, SecureString password, String grant_type) throws IdvException {
MultiValueMap<String, String> body = new LinkedMultiValueMap<String, String>();
body.add(USERNAME, username);
body.add(PASSWORD, (password != null) ? String.valueOf(password.getContent()) : null);
body.add(GRANT_TYPE, grant_type);
com.idv.gateway.api.ssas.rest.client.model.TokenActivationResponse tokenResponse = new com.idv.gateway.api.ssas.rest.client.model.TokenActivationResponse();
TokenActivationResponse response = new TokenActivationResponse();
tokenResponse = restProxy.sendAndReceiveToRestService(body, TOKEN, HttpMethod.POST, com.idv.gateway.api.ssas.rest.client.model.TokenActivationResponse.class);
response = transformGrantTokenResp(tokenResponse);
return response;
}
public TokenActivationResponse transformGrantTokenResp(com.idv.gateway.api.ssas.rest.client.model.TokenActivationResponse response) throws IdvException {
if (response != null) {
TokenActivationResponse resp = new TokenActivationResponse();
resp.getData().getAttributes().setAccess_token(response.getAccess_token());
resp.getData().getAttributes().setToken_type(response.getToken_type());
resp.getData().getAttributes().setExpires_in(response.getExpires_in());
resp.getData().getAttributes().setScope(response.getScope());
return resp;
} else {
IdvError error = new IdvError();
error.setTitle("Token Error");
throw new IdvException(error);
}
}
}
Test Class:
#RunWith(MockitoJUnitRunner.class)
public class OauthTokenControllerTest {
String accessToken = "d6234595-812d-40fc-b519-2e3456543";
Long expiresIn = 2905L;
String userName = "abcd";
String password = "efghijk";
String grant_type = "password";
String tokenType = "bearer";
String scope = "read write";
#Mock
SsasServiceImpl ssasService = new SsasServiceImpl();
#InjectMocks
OauthTokenController controller = new OauthTokenController();
#Before
public void setUp(){
}
TokenActivationResponse resp = new TokenActivationResponse();
#Test
public void testGrantToken() throws IdvException {
resp.getData().getAttributes().setAccess_token(accessToken);
resp.getData().getAttributes().setToken_type(tokenType);
resp.getData().getAttributes().setExpires_in(expiresIn);
resp.getData().getAttributes().setScope(scope);
SecureString sec = new SecureString(password);
Mockito.when(ssasService.grantToken(any(String.class),any(SecureString.class),any(String.class) )).thenReturn(resp);
final TokenActivationResponse response = controller.grantToken(any(String.class),any(String.class),any(String.class));
assertNotNull(response);
}
}
Exception:
Connected to the target VM, address: '127.0.0.1:60951', transport: 'socket'
16:21:38.387 [main] ERROR com.idv.gateway.controller.OauthTokenController - Exception in oauth token granting controller
java.lang.Exception: null
at com.idv.gateway.controller.OauthTokenController.grantToken(OauthTokenController.java:33)
at com.idv.gateway.controller.OauthTokenControllerTest.testGrantToken(OauthTokenControllerTest.java:61)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
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.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.mockito.internal.runners.DefaultInternalRunner$1.run(DefaultInternalRunner.java:79)
at org.mockito.internal.runners.DefaultInternalRunner.run(DefaultInternalRunner.java:85)
at org.mockito.internal.runners.StrictRunner.run(StrictRunner.java:39)
at org.mockito.junit.MockitoJUnitRunner.run(MockitoJUnitRunner.java:163)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
java.lang.AssertionError
at org.junit.Assert.fail(Assert.java:86)
at org.junit.Assert.assertTrue(Assert.java:41)
at org.junit.Assert.assertNotNull(Assert.java:712)
at org.junit.Assert.assertNotNull(Assert.java:722)
at com.idv.gateway.controller.OauthTokenControllerTest.testGrantToken(OauthTokenControllerTest.java:62)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
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.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.mockito.internal.runners.DefaultInternalRunner$1.run(DefaultInternalRunner.java:79)
at org.mockito.internal.runners.DefaultInternalRunner.run(DefaultInternalRunner.java:85)
at org.mockito.internal.runners.StrictRunner.run(StrictRunner.java:39)
at org.mockito.junit.MockitoJUnitRunner.run(MockitoJUnitRunner.java:163)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
Disconnected from the target VM, address: '127.0.0.1:60951', transport: 'socket'
[MockitoHint] OauthTokenControllerTest.testGrantToken (see javadoc for MockitoHint):
[MockitoHint] 1. Unused... -> at com.idv.gateway.controller.OauthTokenControllerTest.testGrantToken(OauthTokenControllerTest.java:60)
[MockitoHint] ...args ok? -> at com.idv.gateway.controller.OauthTokenController.grantToken(OauthTokenController.java:31)
Process finished with exit code -1
I've resolved the issue:
Solution and Fix:
In my TestCase Code, I've replaced the below any(String.class):
Mockito.when(ssasService.grantToken(any(String.class),any(SecureString.class),any(String.class) )).thenReturn(resp);
final TokenActivationResponse response = controller.grantToken(any(String.class),any(String.class),any(String.class));
With (anyString()):
Mockito.when(ssasService.grantToken(anyString(),any(SecureString.class),anyString() )).thenReturn(resp);
final TokenActivationResponse response = controller.grantToken(anyString(),any(String.class),anyString());
One of these Links hepled: Mockito - Invalid use of argument matchers
Also, if you use argument matcher in mockito for one argument, make sure to use for all.

Categories

Resources