junit - Mockito NotAMockException 当它显然是

标签 junit mockito spring-test

我正在使用 Spring Test 框架和 Junit。我有一个用于测试用例的 spring 上下文文件:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({ "classpath:spring/restTestContext.xml",
        "classpath:spring/webserviceContext.xml" })
@PrepareForTest(User.class)
public class RestTestsIT {

// This is a mock
@Autowired private AWSMailService mailService;
...
}

在restTestContext.xml中,我创建了一个AWSMailService类型的bean(实际上是一个模拟):

<bean id="mailService" name="mailService" class="org.mockito.Mockito" factory-method="mock">
    <constructor-arg value="com.acme.utils.email.AWSMailService" />
</bean>

在测试中,我试图验证是否在 mailService 模拟上调用了 sendEmail() 方法,但我收到了 NotAMockException,尽管在对象上调用 toString() 告诉我这是一个模拟:

public void testEmailSent() {
...
// Results in "Mock for AWSMailService, hashCode: 31777764"
System.out.println(mailService.toString());

// Results in NotAMockException
verify(mailService).sendEmail(any(String.class), ...);
}

有谁知道可能导致此问题的原因吗?

谢谢

最佳答案

Spring 是否为这个对象创建了一个代理,以便 Mockito 认为它不是一个模拟,因为你得到了一个 Proxy$34 类作为调用者和你的模拟对象之间的中间人?

关于junit - Mockito NotAMockException 当它显然是,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10316386/

相关文章:

android - 在 Junit for Android 中使用 FEST-assert 的正确方法?

java - 如何在没有 Maven 的情况下设置独立的 Junit 和 Mockito

java - 服务对象没有用数据模拟?

java - 使用 MockBean 清理 Spring Context 缓存失败 loadLibrary

java - TestNG + Spring 测试 : EntityManager return null with testng

java - 模拟返回 Page 接口(interface)的方法

java - JUnit 和类加载器的问题

java - 如何使用mockito/powermockito模拟IamRequest impl类?

java - 运行时错误 PowerMock + Mockito : ProxyFrameworkImpl could not be located in classpath

spring - 通过@import 和@ContextConfiguration 对配置进行分组有什么区别?