0
我對單元測試絕對陌生,並且已經通過有關Mock對象的教程。我試圖測試一個簡單的登錄源代碼,但無法創建適當的單元測試代碼。可有人請提供一些幫助,如果我想測試對不正確的用戶名,密碼正確,正確的用戶名和密碼不正確:使用EasyMock進行單元測試簡單登錄服務
package com.isyn.testsetup;
public interface ApplicationUserService {
public ApplicationUser findByUserName(String userName);
}
package com.isyn.testsetup;
public class ApplicationUser {
private String userName;
private String password;
public ApplicationUser(String userName, String password) {
this.userName = userName;
this.password = password;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
package com.isyn.testsetup;
public class LoginUser {
private ApplicationUserService applicationUserService;
public LoginUser(ApplicationUserService applicationUserService) {
this.applicationUserService = applicationUserService;
}
public boolean validateCredentials(String userName, String password) {
boolean validationResult = false;
try {
ApplicationUser applicationUser = applicationUserService.findByUserName(userName);
if (applicationUser.getPassword().equals(password)) {
validationResult = true;
}
}
catch (Exception e) {
e.printStackTrace();
}
return validationResult;
}
}
我想出了這個測試用例的有效用戶:
package com.isyn.testsetup;
import static org.easymock.EasyMock.eq;
import static org.easymock.EasyMock.expect;
import static org.easymock.EasyMock.replay;
import junit.framework.TestCase;
import org.easymock.EasyMock;
import org.junit.Before;
import org.junit.Test;
public class TestLogIn extends TestCase{
private ApplicationUser applicationUser;
private ApplicationUserService mockUserServiceObj;
@Before
public void setup() {
mockUserServiceObj = EasyMock.createMock(ApplicationUserService.class);
applicationUser = new ApplicationUser("gooduser", "goodpassword");
}
@Test
public void test() {
setup();
expect(mockUserServiceObj.findByUserName(eq("gooduser"))).andReturn(applicationUser);
replay(mockUserServiceObj);
LoginUser testUser = new LoginUser(mockUserServiceObj);
boolean checkStatus = testUser.validateCredentials("gooduser", "goodpassword");
assertTrue(checkStatus);
}
}
我想檢查不正確的憑據,不知道它是否會工作,因爲它顯示意想不到的方法調用!
Need Help!
謝謝您爲此付出時間。所以,因爲我對模擬測試完全陌生,所以我想知道我應該怎麼做檢查測試案例,如 1.錯誤的用戶名,正確的密碼 2.正確的用戶名,錯誤的密碼 3.空的用戶名,空密碼 因爲如果我正在對「baduser」和「goodpassword」進行測試,則顯示錯誤: java.lang.AssertionError: 意外的方法調用ApplicationUserService.findByUserName(「baduser」): ApplicationUserService.findByUserName(「gooduser」):expected :1,actual:0 – 2014-10-02 17:26:24
關於你的第二個問題,如果我沒有調用setup(),它會顯示一個錯誤。你可以試試看。 – 2014-10-02 17:29:35