2
我正在用GWT做这个项目,当我为LogIn方法进行Junit测试时,我得到一个NullPointerException,因为我用HttpServletRequest检查会话。Gwt Junit测试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
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方法checkLogin和我得到的NullPointerException异常。
如何避免这种情况,或者如何在Junit测试中为会话调用HttpServletRequest?
好的改变了方法storeUserInSession与
private 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);
}
}
我同意你的选择,1和4. 这是一个大学项目,我不知道我是否可以使用方法3! 我会尝试方法1和4,当它工作时,我会检查你的答案...如果我遇到一些问题,请在此处张贴或打开另一个问题? (你觉得怎么样?) – Dario
用解决方案编辑!感谢您的支持! – Dario