我刚刚开始使用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
}
}
我得到了异常,因为mock在调用时不起作用(userDao.findUserByEmail(email);在UserAuthentication类中。)
任何人都知道为什么?
答案 0 :(得分:2)
当您同时模拟并验证返回的(来自模拟)表达式应放在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;
}
}