方法Mockito.when()。thenReturn()和Mockito.doreturn()。when()没有返回指定的模拟值

时间:2018-04-20 05:03:33

标签: java spring-boot spring-mongo

    @InjectMocks
    private UserServiceImpl userService;

    @Mock
    private UserRepository  mockUserRepository;



    //private UserServiceImpl userServiceImpl;

    @Before
    public void initMocks() throws Exception {

        MockitoAnnotations.initMocks(this);
        mockUserRepository = Mockito.mock(UserRepository.class);
    }

    @Test
    public void testCreateUser() {

        User user = createUser();
        Mockito.doReturn(user).when(mockUserRepository).findByEmail(user.getEmail());       

        Mockito.when(mockUserRepository.save(user)).thenReturn(user);
        userService.createUser(user);
    }

private User createUser() {

        User user = new User();
        user.setFirstName("Shreya");
        user.setLastName("Mahajan");
        user.setEmail("shreya.mahajan@nitorinfotech.com");
        user.setRole("admin");
        user.setPassword("shreya123");

        return user;

    }

这是我的实际服务方法。在测试它时,我对变量existingUser和response

给出了null
@Override
    public ResponseVO createUser(User user) {
        ResponseVO responseVO = new ResponseVO();
        User existingUser = userRepository.findByEmail(user.getEmail());
        if(user.getEmail() != null){
            if(existingUser != null){
                responseVO.setStatusCode("500");
                responseVO.setMessage("user Already Exists");
            }else{              
                User response = userRepository.save(user);
                if(response == null){
                    responseVO.setStatusCode("400");
                    responseVO.setMessage("Failure");                       
                }else{
                    responseVO.setStatusCode("200");
                    responseVO.setMessage("Success");       
                }
            }           
        }
        return responseVO;
    }

我正在尝试编写测试用例和模拟方法findByEmail()和save()但是在模拟时我没有收到thenreturn()和doreturn()中提到的用户对象。

任何人都可以帮忙。

1 个答案:

答案 0 :(得分:1)

以下是您可以尝试的事情:

请删除mockUserRepository = Mockito.mock(UserRepository.class);作为其冗余。

而不是

Mockito.doReturn(user).when(mockUserRepository).findByEmail(user.getEmail()); 

这样做

Mockito.doReturn(user).when(mockUserRepository).findByEmail(Mockito.any());