【发布时间】:2018-09-27 13:51:25
【问题描述】:
当模拟注入到控制器中的服务时,服务方法应该返回一个模拟对象,类似于:
public class EmptyInterventionServiceMock implements InterventionService {
@Override
public Intervention findByInvoiceNumber(String invoiceNumber, String language) {
return mockedIntervention(invoiceNumber, language);
}
protected Intervention mockedIntervention(String invoiceNumber, String language) {
return mock(Intervention.class);
}
}
是否可以模拟上述模拟对象 (Intervention) 返回的某些值来测试它们是否应该出现在生成的 JSON 模板中?
例如,取决于Intervention是否有spare parts、services、states(它们都只是其他对象的集合)等。如果有,JSON应该包含对应的键:@987654327 @、states: [{}]等
在测试中获取模拟对象并将其返回值存根会很好。目前我认为实现这一目标的唯一方法是创建一个单独的Mock 服务类并将其注入测试类,如下所示:
public class InterventionsControllerSpec extends ControllerSpec {
@Before
public void before() {
Injector injector = injector().bind(InterventionService.class).to(BaseInterventionServiceMock.class).create();
}
其中BaseInterventionServiceMock 只是扩展EmptyInterventionServiceMock 并通过覆盖其mockedIntervention 方法来存根一些方法返回值:
public class BaseInterventionServiceMock extends EmptyInterventionServiceMock {
@Override
protected Intervention mockedIntervention(String invoiceNumber, String language) {
Intervention intervention = mock(Intervention.class);
when(intervention.getString("ITV_DOCUMENT_NUMBER")).thenReturn("123");
when(intervention.getString("ITV_INVOICE")).thenReturn(invoiceNumber);
...
etc.
由于它远非理想,我想知道是否有 DRYer 方法可以做到这一点?
谢谢。
【问题讨论】:
-
无论如何,模拟值不能以这种方式工作:
when(intervention.getString("itv_document_number")).thenReturn("123");在模板中显示它时像这样:"document_number" : "${intervention.itv_document_number!}"。似乎如果不覆盖模型中相应的getter方法并模拟该方法,它将无法正常工作。有任何想法吗 ?还是我错过了什么?
标签: activeweb