目前,我想要完成一張測試驅動開發的課程,並跑進用下面的代碼有問題:單元測試空指針異常
package stockInformation;
public class StockInformation {
String companyName;
public String getCompanyName() {
return companyName;
}
private WebService webService;
// Constructor
public StockInformation(int userID) {
if (webService.authenticate(userID)){
//Do nothing
} else {
companyName = "Not Allowed";
}
}
}
(如果 - 否則甚少做的目的以便稍後在作業中對其進行重構)
由另一個團隊開發的Web服務因此需要模擬 package stockInformation;
public interface WebService {
public boolean authenticate(int userID);
}
測試類
package stockInformation;
import org.junit.Before;
import org.junit.Test;
import static org.easymock.EasyMock.*;
import static org.junit.Assert.*;
public class StockInformationTest {
WebService mockWebService;
StockInformation si;
@Before
public void setUp() throws Exception {
mockWebService = createMock(WebService.class);
}
@Test
public void testUserIdAuthentication() {
int userID = -2;
si = new StockInformation(userID);
expect(mockWebService.authenticate(userID)).andReturn(false);
replay(mockWebService);
assertEquals("Not Allowed", si.getCompanyName());
verify(mockWebService);
}
}
當我運行單元測試我終於找到一個NullPonterException:
if (webService.authenticate(userID)){
和
si = new StockInformation(userID);
我想要的單元測試通過:) 任何hel p讚賞。
你有一個關於價值論代碼運行時的'webService'?你認爲這個價值是什麼? –
webService只是表示將有一個方法authenticate(int userId)的接口,它根據給定的userId是否符合驗證返回true或false。在WebService接口中不應該寫入任何實際的功能,因此在單元測試中使用andReturn。 –
我明白這一點。代碼運行時,您認爲'webService'有哪些值? –