-2

Here is my Controller Class:

@RequestMapping(value="/administration", method=RequestMethod.GET)
public ModelAndView adminstrationPage(HttpServletRequest request){
    ModelAndView mv = new ModelAndView();
    mv.setViewName("administration");

    Optional<User> uo = userRepository.findOneByName(request.getUserPrincipal().getName());
    ... return mv;
}

Here is my LoginControllerTest:

    @InjectMocks
        LoginController loginController;

        @Mock
        private LoginService loginService;

        @Mock
        private UserRepository userRepository;

        @Mock
        User user;

        MockMvc mockMvc;
    @Test
        public void administartion() throws Exception{

Mockito.when(userRepository.findOneByName("test")).thenReturn(Optional.of(user));

            mockMvc.perform(get("/administration"))
            .andExpect(status().isOk());
        }

Now getting nested exception is java.lang.NullPointerException. Please help me.

Amit
  • 1,540
  • 1
  • 15
  • 28
  • Please paste complete code of LoginControllerTest.java – Taras Velykyy Jul 24 '17 at 09:38
  • Did you annotate your class with @RunWith(MockitoJUnitRunner.class) as suggested at https://www.tutorialspoint.com/mockito/mockito_junit_integration.htm – DmiN Jul 24 '17 at 09:38
  • What is the point in calling setters on a mock? Makes no sense to me. – Tom Jul 24 '17 at 09:44
  • I have updated my code... but still same problem – Amit Jul 24 '17 at 10:14
  • Possible duplicate of [What is a NullPointerException, and how do I fix it?](https://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – Tom Jul 24 '17 at 10:52

2 Answers2

0

When mocking user repository, instead of userRepository.findOneByName("") try userRepository.findOneByName(anyString()). And don't forget to init mocks in before method, MockitoAnnotations.initMocks(this);

Vadym Dudnyk
  • 162
  • 3
  • I have checked with userRepository.findOneByName(anyString()) and use MockitoAnnotations.initMocks(this); into before method but still same problem. NullPointerException – Amit Jul 24 '17 at 09:56
0
    user.setId(100000L);
    user.setName("testName");
    user.setEmail("testEmail@gmail.com");

Since user is a mock these statements are useless.

Either create a real User object (which is prefered if it is a simple DTO) or define the user mocks behavior using when(user.getXXX()).thenhReturn(xxx) or doReturn(xxx).when(user).getXXX();

Timothy Truckle
  • 15,071
  • 2
  • 27
  • 51