我不能嘲笑 属性 的 class

I can't mock property of class

我刚开始使用 spock,我遇到了一个问题..

    public class UserAuthentication {
        private UserDAO userDao;

        public boolean authenticateUser(String email, String password){
            User user = userDao.findUserByEmail(email);

            if(password.equals(user.getDecodedPassword())){
                return true;
            }
            return false;
        }
}


public interface UserDAO {

    User findUserByEmail(String login);

    void saveUser(User user);
}

public class User {

    private String email;
    private String decodedPassword;

    public User(String email, String decodedPassword) {
        this.email = email;
        this.decodedPassword = decodedPassword;
    }(...)

不幸的是我的测试抛出 NullPointerException:

import java.text.SimpleDateFormat
import spock.lang.Specification

class UserAuthenticationTest extends Specification {

    def "Authenticating correct user" () {
        setup:
        def email = "email@email.com"
        def password = "qwerty1234"

        def userDao = Mock(UserDAO)
        userDao.findUserByEmail(email) >> new User(email, password)

        def userAuthenticator = new UserAuthentication()
        userAuthenticator.setUserDao(userDao)

        when:
        def result = userAuthenticator.authenticateUser(email, password)

        then:
        1 * userDao.findUserByEmail(email)
        result == true
    }

}

我遇到了异常,因为调用时模拟不起作用(userDao.findUserByEmail(电子邮件);在 UserAuthentication class 中)。

有人知道为什么吗?

当你同时模拟和验证返回的(从模拟)表达式时,应该放在 then 块下。 Here 是文档,您可以在下面找到更正的代码:

@Grab('org.spockframework:spock-core:0.7-groovy-2.0')
@Grab('cglib:cglib-nodep:3.1')

import spock.lang.*
import java.text.SimpleDateFormat

class UserAuthenticationTest extends Specification {

    def "Authenticating correct user" () {
        setup:
        def email = "email@email.com"
        def password = "qwerty1234"

        def userDao = Mock(UserDAO) 

        def userAuthenticator = new UserAuthentication()
        userAuthenticator.userDao = userDao

        when:
        def result = userAuthenticator.authenticateUser(email, password)

        then:
        1 * userDao.findUserByEmail(email) >>  new User(email, password)
        result == true
    }
}

public class UserAuthentication {
    UserDAO userDao;

    public boolean authenticateUser(String email, String password){
        User user = userDao.findUserByEmail(email);        
        return password.equals(user.getDecodedPassword());
    }
}

public interface UserDAO {

    User findUserByEmail(String login);

    void saveUser(User user);
}

public class User {

    private String email;
    private String decodedPassword;

    public User(String email, String decodedPassword) {
        this.email = email;
        this.decodedPassword = decodedPassword;
    }

    public String getDecodedPassword() {
        return decodedPassword;
    }
}