【发布时间】:2016-03-10 06:16:26
【问题描述】:
我正在研究一个存储一些会话信息以与第三方 API 通信的类。所以,基本上它有很多行为和很少的状态需要维护。这是它的一种方法:
public LineItem getLineItem(
String networkId, String lineItemId) throws ApiException_Exception {
LineItem lineItem = null;
session.setCode(networkId);
LineItemServiceInterface lineItemService = servicesInterface.lineItemService(session);
StatementBuilder statementBuilder =
new StatementBuilder()
.where("id = " + lineItemId.trim())
.orderBy("id ASC")
.limit(StatementBuilder.SUGGESTED_PAGE_LIMIT);
LineItemPage lineItemPage =
lineItemService.getLineItemsByStatement(statementBuilder.toStatement());
if (lineItemPage != null && lineItemPage.getResults() != null) {
lineItem = lineItemPage.getResults().get(0);
}
return lineItem;
}
我被困在如何测试这个方法上,它对第三方对象有太多的隐式依赖。这些对象很难自己创建。另一个大问题是getLineItemByStatement 在幕后进行网络调用(SOAP)。
就我而言,我正在尝试模拟外部服务并检查服务是否使用正确的Statement 请求数据,除此之外我无法做任何事情,因为我的对象没有状态更改,并且大部分交互的对象是第三方。
问题
在这些情况下,最令人困惑的是我的班级应该对合作者了解多少?我的测试需要了解多少关于我的测试方法使用的对象?
示例:
@Test
public void shouldGetLineItem() throws ApiException_Exception {
when(servicesInterface.lineItemService(dfpSession)).thenReturn(mockLineItemService);
dfpClient.getLineItem("123", "123");
Statement mockStatement = mock(Statement.class);
Statement statement =
new StatementBuilder()
.where("id = 123")
.orderBy("id ASC")
.limit(StatementBuilder.SUGGESTED_PAGE_LIMIT)
.toStatement();
verify(dfpSession).setNetworkCode("123");
verify(mockLineItemService).getLineItemsByStatement(isA(Statement.class));
}
我们可以看到我的测试对我的测试方法了解太多。
更新 1
一段时间后,我发现对我的类进行单元测试变得太难了,因为对 LineItem 的引用分散在各处,而且由于 LineItem 与其他对象有很多深层链接,因此很难创建自己的对象,因此我有决定创建一个域模型,其中包含我的应用程序的相关详细信息。
public LineItemDescription getLineItem(String networkId, String lineItemId)
throws ApiException_Exception {
dfpSession.setNetworkCode(networkId);
LineItemServiceInterface lineItemService = servicesInterface.lineItemService(dfpSession);
return buildLineItemDescription(
getFirstItemFromPage(lineItemService.getLineItemsByStatement(buildStatement(lineItemId))));
}
【问题讨论】:
-
Mocking 对我来说似乎是正确的答案。具体问题是什么?
-
@JBNizet 目前更新了问题和单元测试。
标签: java unit-testing tdd mockito guice