【发布时间】:2016-02-05 12:39:27
【问题描述】:
我目前正在尝试完成一项测试驱动开发课程,但遇到了以下代码的问题:
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)){
和
si = new StockInformation(userID);
我希望单元测试通过 :) 任何帮助表示赞赏。
【问题讨论】:
-
你对代码运行时
webService的值有理论吗?您认为该值是多少? -
webService 只是表示将具有方法 authenticate(int userId) 的接口,该方法根据给定的 userId 是否满足验证返回 true 或 false。 WebService 接口中不应编写任何实际功能,因此在单元测试中使用 andReturn。
-
我明白这一点。 你认为
webService在代码运行时有什么价值? -
webService被声明为WebService类型的值。false是WebService类型的有效值吗? -
深入了解 :)
标签: unit-testing tdd easymock