2016-02-05 99 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);