使用Mock和InvocationOnMock进行单元测试

时间:2019-01-21 12:41:45

标签: java spring-boot

我是Java Spring的新手,我需要Mockito的指导。

我试图测试我的服务层,但是它仍然无法验证模拟用户名和电子邮件地址。

我目前对应该如何正确处理感到非常困惑。

谢谢!

  

UserService.java

package com.example.newproject.newproject.service;

import com.example.newproject.newproject.entity.User;

import java.util.List;

public interface UserService {
    boolean addUser(String username,String email);
    List<User> viewAllUsers();
}
  

UserServiceImpl.java

package com.example.newproject.newproject.service.impl;

import com.example.newproject.newproject.entity.User;
import com.example.newproject.newproject.repository.UserRepository;
import com.example.newproject.newproject.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class UserServiceImpl implements UserService {
    @Autowired
    private UserRepository userRepository;


    @Override
    public boolean addUser(String username, String email) {
        if(userRepository.findByUsernameAndEmail(username, email) == null)
        {
            User user = new User();
            user.setUsername(username);
            user.setEmail(email);
            userRepository.save(user);
            return false;

        }else{
            return true;
        }

    }

    @Override
    public List<User> viewAllUsers() {
        return userRepository.findAll();
    }
}
  

我的模拟

@Test
public void testAddUser(){
    Mockito.when(userRepository.findByUsernameAndEmail("Google","google@google.com")).then(invocationOnMock ->  {

        User user = new User();
        return user;
    });

    boolean result =  userService.addUser("Google","google@google.com");
    Assert.assertFalse(result);

    Mockito.verify(userRepository, Mockito.times(1)).save(userArgumentCaptor.capture());
    User user = userArgumentCaptor.getValue();
    Assert.assertEquals("Google", user.getUsername());
    Assert.assertEquals("google@google.com", user.getEmail());
}

我得到的错误是

  java.lang.AssertionError

运行期间

0 个答案:

没有答案