【发布时间】:2015-08-08 18:23:02
【问题描述】:
我正在编写端点单元测试,其中大多数有一个应该模拟的外部 Web 服务,或者其中的几个。
起初,我在测试中创建模拟,当端点测试仅使用一个外部服务时,模拟创建基本上是一个衬垫。
随着用例变得越来越复杂,我需要为单个端点测试模拟几个服务和异常。 我已经将这些模拟创建放在所有扩展单个工厂和使用构建器模式的工厂之后。
在该基础工厂中有一个内部类,我将其用作MockWebServiceServer 的构建器。
protected class MultiStepMockBuilder {
private List<Object> mockActions = new ArrayList<Object>();
private WebServiceGatewaySupport gatewaySupport;
protected MultiStepMockBuilder(WebServiceGatewaySupport gatewaySupport) {
this.gatewaySupport = gatewaySupport;
}
protected MultiStepMockBuilder exception(RuntimeException exception) {
mockActions.add(exception);
return this;
}
protected MultiStepMockBuilder resource(Resource resource) {
mockActions.add(resource);
return this;
}
protected MockWebServiceServer build() {
MockWebServiceServer server = MockWebServiceServer.createServer(gatewaySupport);
for(Object mock: mockActions) {
if (mock instanceof RuntimeException) {
server.expect(anything()).andRespond(withException((RuntimeException)mock));
}
else if (mock instanceof Resource)
{
try
{
server.expect(anything()).andRespond(withSoapEnvelope((Resource) mock));
} catch (IOException e) {e.printStackTrace();}
}
else
throw new RuntimeException("unusuported mock action");
}
return server;
}
}
}
所以我现在可以做这样的事情来创建模拟:
return new MultiStepMockBuilder(gatewaySupport).resource(success).exception(new WebServiceIOException("reserve timeout"))
.resource(invalidMsisdn)
.build();
我在这个实现中遇到的问题是依赖于instanceof 运算符,我从不在equals 之外使用它。
在这种情况下是否有 instanceof 运算符的替代方法?从关于instanceof 主题的问题中,每个人都认为它只能在equals 中使用,因此我觉得这是“肮脏”的解决方案。
是否有 instanceof 运算符的替代方案,在 Spring 中或作为不同的设计,同时保留 fluent interface 用于创建模拟?
【问题讨论】:
标签: java spring unit-testing instanceof