目前,我想要完成一张测试驱动开发的课程,并跑进用下面的代码有问题:单元测试空指针异常
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'有哪些值? –