如何用Mockito代替JUnit Test Java中的一个类

时间:2018-01-12 17:33:55

标签: java spring junit mockito stub

我试图在JUnit的测试会话期间替换正确使用Mockito,而不是存根一个类。 不幸的是,在网上有很多关于Mockito的教程,但是对于存根方法来说更少,我想学习这种技术。

此测试由Mockito完成:

 @Test
public void addWrongNewUserSpaceInUsername() throws Exception {

    when(userValidator.isValidUsername(user.getUsername())).thenReturn(false);

    try {
        mockMvc.perform(
                post("/register")
                        .contentType(MediaType.APPLICATION_JSON)
                        .content(asJsonString(user)
                        ));
    } catch (Exception e) {
        Assert.assertTrue(e.getCause() instanceof UsernameNotValidException);
    }
}

澄清这些是涉及的课程:

1)控制器

   @RestController
public class UserController {

    @Autowired
    RepositoryUserDB repositoryUserDB;

    @Autowired
    UserValidator userValidator;

    @RequestMapping(value = "/register", method = RequestMethod.POST)
    public User createUser(@RequestBody User user) {


        if (userValidator.isValidUsername(user.getUsername())) {

            if(!userValidator.isValidPassword(user.getPassword())){
                throw new PasswordNotValidException();
            }

            if(userValidator.isValidDateOfBirth(user.getDateOfBirth()) == false){
                throw new DOBNotValidException();
            }

            // se lo user e' gia' presente
            if (repositoryUserDB.getUserByUsername(user.getUsername()) == null) {
                return repositoryUserDB.createUser(user);
            }
            throw new UsernameAlreadyExistException();
        } else throw new UsernameNotValidException();

    }
}

2)回购界面:

public interface RepositoryUserDB {

    User getUserByUsername(String username);

    User createUser(User user);
}

3)回购:

@Component

    public class MemoryUserDB implements RepositoryUserDB{

        Map<String, User> repo;

        public MemoryUserDB() {
            this.repo = new HashMap<>();
        }

        @Override
        public  User getUserByUsername(String username) {
            return repo.get(username);
        }

        @Override
        public User createUser(User user) {
            repo.put(user.getUsername(),user);
            return repo.get(user.getUsername());
        }
    }

4)验证员:

   @Component
public class UserValidator {

    public boolean isValidUsername(String username) {
        return username.matches("^[a-zA-Z0-9]+$");
    }

    public boolean isValidPassword(String pwd) {
        if (pwd == null)
            return false;
        return pwd.matches("^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d){4,}.+$");
    }

    public boolean isValidDateOfBirth(String DOB) {
        return DOB.matches("^(?:(?:(?:0?[13578]|1[02])(\\/|-|\\.)31)\\1|(?:(?:0?[1,3-9]|1[0-2])(\\/|-|\\.)(?:29|30)\\2))(?:(?:1[6-9]|[2-9]\\d)?\\d{2})$|^(?:0?2(\\/|-|\\.)29\\3(?:(?:(?:1[6-9]|[2-9]\\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))$|^(?:(?:0?[1-9])|(?:1[0-2]))(\\/|-|\\.)(?:0?[1-9]|1\\d|2[0-8])\\4(?:(?:1[6-9]|[2-9]\\d)?\\d{2})$");
    }
}

5)ResEntityExceptionHandler

    @ControllerAdvice
public class RestEntityExceptionHandler {

    @ExceptionHandler(UsernameNotValidException.class)
    @ResponseStatus(value = HttpStatus.FORBIDDEN, reason = "username wrong")
    public void handleUsernameException() {
    }

    @ExceptionHandler(UsernameAlreadyExistException.class)
    @ResponseStatus(value = HttpStatus.BAD_REQUEST, reason = "the username is already presents")
    public void handleUsername() {
    }

    @ExceptionHandler(PasswordNotValidException.class)
    @ResponseStatus(value = HttpStatus.FORBIDDEN, reason = "password wrong")
    public void handlePasswordException() {
    }

    @ExceptionHandler(DOBNotValidException.class)
    @ResponseStatus(value = HttpStatus.FORBIDDEN, reason = "Date Of Birth wrong")
    public void handleDOBException(){
    }

}

1 个答案:

答案 0 :(得分:1)

理论上,对于你的用例,存根方法应该相当简单 但是当你依赖使用Spring bean容器的Spring Boot测试时,事情真的很难设置,因为你应该找到一种方法来在容器中注入mocked bean来替换实际的bean:UserValidator
Spring Boot测试中的模拟通常依赖于Spring Boot MockBean 它不是一个模拟的嘲笑,但不是很远 要了解与Mockito模拟的差异,您可以参考to this question

使用框架提供了许多开箱即用的功能,但也限制了您自己,因为您想绕过框架功能。

假设您没有使用Spring Boot执行集成测试,而是使用真正的单元测试(因此没有Spring引导容器),可以通过这种方式执行。

您可以定义UserValidator.isValidUsername()的自定义实现,而不是模拟UserValidator,它会在测试中按预期方式返回方法返回。
最后,Mockito或任何模拟框架为您做什么。

所以这是存根类:

public class UserValidatorStub extends UserValidator {

    private String expectedUsername;
    private boolean isValidUsername;

    public UserValidatorStub(String expectedUsername, boolean isValidUsername){
          this.expectedUsername = expectedUsername;
          this.isValidUsername = isValidUsername;
    }
    public boolean isValidUsername(String username) {
        if (username.equals(expectedUsername)){
           return isValidUsername;
        }
        // as fallback, it uses the default implementation but you may return false or null as alternative
       return super.isValidUsername(username);
    }

}

它接受一个构造函数来存储传递给stubbed方法的预期参数和要返回的stubbed结果。

现在,您可以在这里编写测试:

 @Test
public void addWrongNewUserSpaceInUsername() throws Exception {

    // inject the mock in the class under test
    UserController userController = new UserController(new UserValidatorStub(user.getUsername(), false));
    try {
        userController.createUser(user);
    } catch (Exception e) {
        Assert.assertTrue(e.getCause() instanceof UsernameNotValidException);
    }
}

请注意,该示例依赖于UserController中的构造函数注入来设置依赖项。