2016-02-05 103 views
1

目前,我想要完成一張測試驅動開發的課程,並跑進用下面的代碼有問題:單元測試空指針異常

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讚賞。

+0

你有一個關於價值論代碼運行時的'webService'?你認爲這個價值是什麼? –

+0

webService只是表示將有一個方法authenticate(int userId)的接口,它根據給定的userId是否符合驗證返回true或false。在WebService接口中不應該寫入任何實際的功能,因此在單元測試中使用andReturn。 –

+0

我明白這一點。代碼運行時,您認爲'webService'有哪些值? –

回答

0

您從未在類StockInformation中設置private WebService webservice。在StockInformation構造函數中使用它,它的值爲null。

0

您應該以某種方式爲StockInformation類的webService字段賦值。

這可以通過反射或setter方法來完成:在測試執行期間

public void setWebService(WebService webService) { 
    this.webService = webService; 
} 

然後,設置一個模擬的WebService實例StockInformation例如:

si = new StockInformation(userID); 
si.setWebService(mockWebService);