Unit testing 单元测试空指针异常
我目前正试图完成一项测试驱动开发课程,但遇到了以下代码问题:Unit testing 单元测试空指针异常,unit-testing,tdd,easymock,Unit Testing,Tdd,Easymock,我目前正试图完成一项测试驱动开发课程,但遇到了以下代码问题: package stockInformation; public class StockInformation { String companyName; public String getCompanyName() { return companyName; } private WebService webService; // Constructor public StockInformation(int use
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";
}
}
}
(if-else故意做得很差,以便我可以在以后的作业中重构它)
“由另一个团队开发”的Web服务需要模仿
包装库存信息
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)){
及
我希望单元测试通过:)
感谢您的帮助。您从未在课堂
股票信息中设置私有网络服务。您在StockInformation
构造函数中使用此函数,其值为空。您从未在类StockInformation
中设置私有WebService
。您在StockInformation
构造函数中使用它,它的值为null。您应该以某种方式为StockInformation类的webService字段赋值
这可以通过反射或setter方法完成:
public void setWebService(WebService webService) {
this.webService = webService;
}
然后,在测试执行期间,将模拟WebService实例设置为StockInformation实例:
si = new StockInformation(userID);
si.setWebService(mockWebService);
您应该以某种方式为StockInformation类的webService字段赋值
这可以通过反射或setter方法完成:
public void setWebService(WebService webService) {
this.webService = webService;
}
然后,在测试执行期间,将模拟WebService实例设置为StockInformation实例:
si = new StockInformation(userID);
si.setWebService(mockWebService);
你有关于webService
在代码运行时的价值的理论吗?您认为这个值是什么?webService只是表示一个接口,该接口将有一个方法authenticate(int userId),该方法根据给定的userId是否满足验证条件返回true或false。WebService接口中不应该编写任何实际的功能,因此在单元测试中使用andReturn。我理解这一点。当代码运行时,您认为webService
具有哪个值?webService
被声明为webService
类型的值。false
是WebService
类型的有效值吗?追根究底:)你有关于WebService
在代码运行时的值的理论吗?您认为这个值是什么?webService只是表示一个接口,该接口将有一个方法authenticate(int userId),该方法根据给定的userId是否满足验证条件返回true或false。WebService接口中不应该编写任何实际的功能,因此在单元测试中使用andReturn。我理解这一点。当代码运行时,您认为webService
具有哪个值?webService
被声明为webService
类型的值。false
是否为WebService
类型的有效值?请转至底部:)