当模拟注入控制器的服务时,服务方法应该返回一个模拟对象,如下所示:
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 模板中?
例如,取决于 if Intervention
has spare parts
, services
, states
(它们都只是其他对象的集合)等。如果是这样,JSON 应该包含相应的键:services: [{....}]
,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 方法可以做到这一点?
谢谢你。