我正在使用GWT进行这个项目,当我为LogIn方法进行Junit测试时,我得到一个NullPointerException,因为我用HttpServletRequest检查会话。
这里是Junit测试
private void checkLoginTest() {
UsersServiceImpl USI = new UsersServiceImpl();
UserDTO userDTO1 = new UserDTO();
UserDTO userDTO2 = new UserDTO();
User user1 = new User("username1", "password1", "email1",
"aa", "aa", "aa", "aa", UserRights.USER);
User user2 = new User("username2", "password2", "email2",
"aa", "aa", "aa", "aa", UserRights.USER);
userDTO1.setUser(user1);
userDTO2.setUser(user2);
UserDTO insertedUser1 = USI.register(userDTO1);
UserDTO insertedUser2 = USI.register(userDTO2);
/*
* Check login success
*/
Assert.assertNotNull(USI.checkLogin("username1", "password1"));
Assert.assertNotNull(USI.checkLogin("username2", "password2"));
//Wrong password below
Assert.assertNull(USI.checkLogin("username2", "ciaone"));
/*
* Check user returned by login
*/
/*Assert.assertEquals(user1.getUsername(), USI.checkLogin("username1", "password1"));
Assert.assertEquals(user2.getUsername(), USI.checkLogin("username2", "password2"));*/
}
这里是来自UsersServiceImpl的方法checkLogin
public UserDTO checkLogin(String username, String password) {
// boolean check = false;
UserDTO checkedUser = new UserDTO();
mapDB.begin();
Map<String, User> userMap = mapDB.getDB().createTreeMap("UserMap")
.makeOrGet();
if (userMap.containsKey(username)) {
// Controllo se la password è corretta per quello username
checkedUser.setUser(userMap.get(username));
if (checkedUser.getUser().getPassword().equals(password)) {
// check = true;
checkedUser.setLogged(true);
// Salvo la sessione utente
storeUserInSession(checkedUser);
} else {
checkedUser.setUser(null);
}
} else {
checkedUser.setUser(null);
}
mapDB.end();
return checkedUser;
}
private void storeUserInSession(UserDTO user) {
HttpServletRequest httpServletRequest = this.getThreadLocalRequest();
HttpSession session = httpServletRequest.getSession(true);
session.setAttribute("user", user);
}
storeUserInSession返回null,我得到NullPointerException。
我如何避免这种情况,或者如何在Junit测试中为会话调用HttpServletRequest?
确定用
更改方法storeUserInSessionprivate void storeUserInSession(UserDTO user) {
//Junit test ritorna NullPointerException
//In questo modo funziona
try {
HttpServletRequest httpServletRequest = this.getThreadLocalRequest();
HttpSession session = httpServletRequest.getSession(true);
session.setAttribute("user", user);
} catch (Exception e) {
System.err.println("Errore creazione HttpServeletRequest");
e.printStackTrace();
}
}
或者这个也可以很好
private void storeUserInSession(UserDTO user) {
HttpServletRequest httpServletRequest = this.getThreadLocalRequest();
if( httpServletRequest != null){
HttpSession session = httpServletRequest.getSession(true);
session.setAttribute("user", user);
}
}
答案 0 :(得分:1)
您的问题有不同的解决方案:
storeUserInSession
的可见性更改为protected
,从Class
派生,并更改测试方法。storeUserInSession
NullPointer安全并返回true或false。我会使用方式1或4,因为这将是最简单的方法。
我认为最优雅的方式是3,但你需要学习一个模拟框架。