unit-testing - 使用 Spring 注入(inject) EasyMock 模拟导致 ClassCastException

标签 unit-testing spring dependency-injection mocking easymock

我试图让 Spring 在我的单元测试中注入(inject) EasyMock 模拟。

在我的 applicationContext.xml 中,我有这个:

<bean id="mockService"  class="org.easymock.EasyMock" factory-method="createMock"  name="MockService">
    <constructor-arg index="0" value="my.project.Service"/>
</bean>

在我的单元测试中,我有这个:
@Autowired
@Qualifier("mockService")
private Service service;

public void testGetFoo() {
    Foo foo = new Foo();

    expect(service.findFoo()).andReturn(foo);
    replay(service); // <-- This is line 45, which causes the exception

    // Assertions go here...
}

当我尝试运行我的测试时,我得到了这个堆栈跟踪:
java.lang.ClassCastException: org.springframework.aop.framework.JdkDynamicAopProxy
at org.easymock.EasyMock.getControl(EasyMock.java:1330)
at org.easymock.EasyMock.replay(EasyMock.java:1279)
at TestFooBar.testGetFoo(TestVodServiceLocator.java:45)

我对 Spring 和 EasyMock 都很陌生,但在我看来,错误是由 EasyMock 试图调用一个假定为 EasyMock 实例的方法引起的,但实际上是由 Spring 创建的动态代理。据我了解,动态代理仅实现接口(interface)中定义的方法,在本例中为 Service 接口(interface)。

我不明白的是from what I read (也是 here ),至少我想要实现的目标似乎是可能的。

所以我的问题是:我没有做什么或者我做错了什么?

最佳答案

您还可以创建一个辅助方法来从 Spring 代理中解开 EasyMock 代理以定义预期的行为,然后:

public static <T> T unwrap(T proxiedInstance) {
  if (proxiedInstance instanceof Advised) {
    return unwrap((T) ((Advised) proxiedInstance).getTargetSource().getTarget());
  }

  return proxiedInstance;
}

注意 recusive 调用,因为在最坏的情况下,您在实际目标周围有多个代理。

关于unit-testing - 使用 Spring 注入(inject) EasyMock 模拟导致 ClassCastException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/920281/

相关文章:

c# - 在异步委托(delegate)中断言异常

java - 使用 SpringBatch JdbcCursorItemReader 并将 List 作为 NamedParameters

spring - 为映射和/或嵌套对象自定义 Spring @RequestParam 反序列化

gradle - 无法获得分类依赖

c# - .NET Core DI,将参数传递给构造函数的方法

c# - 使用 Entity Framework 将测试项目添加到 MVC

java - 为什么 Mockito 对 InputStreams 的行为很奇怪?

node.js - 使用Sinon 模拟 Knex 查询

java - org.springframework.data.mapping.PropertyReferenceException : No property update found for type User

c# - 具有非接口(interface)的构造函数参数的依赖注入(inject)