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