我正在尝试对基于 Spring MVC 的 Controller 进行单元测试。 该 Controller 调用服务。该服务实际上是远程的,并通过 JSON-RPC 公开给 Controller ,特别是 com.googlecode.jsonrpc4j.spring.JsonProxyFactoryBean
Controller 具有:
@Controller
@RequestMapping("/users")
public class UserController {
/**
* ID manager service that will be used.
*/
@Autowired
IdMService idMService;
...
@ResponseBody
@RequestMapping(value = "/{userId}", method = GET)
public UserAccountDTO getUser(@PathVariable Long userId, HttpServletResponse response) throws Exception {
try {
return idMService.getUser(userId);
} catch (JsonRpcClientException se) {
sendJsonEncodedErrorRepsonse(response, se);
return null;
}
}
...
}
spring 配置提供这样的 IdMService:
<!-- Create the proxy for the Access Control service -->
<bean class="com.googlecode.jsonrpc4j.spring.JsonProxyFactoryBean">
<property name="serviceUrl" value="${access_control.service.url}" />
<property name="serviceInterface" value="com.phtcorp.service.accesscontrol.IdMService" />
</bean>
因此,注入(inject) Controller 的 IdMService 实际上是一个 JSON-RPC 代理,实现了 IdMService 接口(interface)。
我想测试 Controller ,但模拟 IdMService。我有这个:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:/test-context.xml" })
@SuppressWarnings("javadoc")
public class TestUserController {
@Autowired
private ApplicationContext applicationContext;
private HandlerAdapter handlerAdapter;
private MockHttpServletRequest request;
private MockHttpServletResponse response;
@Mocked IdMService service;
@Test
public void getUser() throws Exception {
request.setMethod(RequestMethod.GET.name());
request.setRequestURI("/users/1");
HandlerMethod handler = (HandlerMethod) getHandler(request);
handlerAdapter.handle(request, response, handler);
new Verifications() {{
service.getUser(1L); times=1;
}};
}
...
}
但是,我发现注入(inject)到 Controller 中的 IdMService 并不是一个模拟,它毕竟是一个 JsonRpcProxy。我已经以这种方式成功测试了不同的 Controller ,但该 Controller 不使用其服务的代理。
所以问题是:如何使用 jmockit 来将模拟 IdMService 注入(inject)到 UserController 中?请注意,我不会在任何地方亲自实例化 UserController; spring/spring-mvc 就是这样做的。
感谢您的帮助!
最佳答案
如果您正在对 UserController 进行单元测试,为什么不自己实例化它呢。将 Spring 排除在外,然后单独测试它。
您在这里并不是在测试 UserController,而是在测试它的 Spring 连接及其请求映射。
关于spring - 如何模拟 Spring 注入(inject)的服务代理?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14428968/