【问题标题】:How to force execution of overriden method of a mocked autowired field in JUnit tests?如何在 JUnit 测试中强制执行模拟自动装配字段的覆盖方法?
【发布时间】:2019-05-11 21:41:16
【问题描述】:

我有一个扩展 HandlerInterceptorAdapter 的 CacheInterceptor 类。这个类有一个自动装配的缓存:

// CacheInterceptor.java
public class CacheInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    private Cache<String, String> myCache;

    ...
}

这个 bean 定义发生在 CachingConfiguration 类中。在这个类中,由于项目需要额外的行为,我重写了缓存写入方法。

// CachingConfiguration.java
public class CachingConfiguration {

    @Bean(name = "myCache")
    public Cache<String, String> getMyCache() {
        ...

        CacheWriter<String, String> writer = new CacheWriter<String, String>() {

            @Override
            public void write(String key, String value) throws Exception {
                object.persist();
                ...
            }
    }
}

然后我有一个 CacheInterceptorTest 类,我在其中模拟 myCache 因为在某些情况下我需要强制返回值。

// CacheInterceptorTest.java
@ContextConfiguration(classes = {
        CachingConfiguration.class
})

public class CacheInterceptorTest {

    @MockBean
    private Cache<String, String> myCache;
}

这适用于我的大部分测试。但是,有一项特定的测试需要在将值放入 Cache 时调用 getMyCache 中的 write() 方法。但是因为我是在嘲笑它,所以它使用的是 Cache.write() 的原始实现。

我怎样才能做到这一点?

【问题讨论】:

  • 也许你想描述什么测试需要这种行为以及为什么。

标签: java spring-boot junit spring-test


【解决方案1】:

模拟是一个独立的实现,它没有被覆盖的方法,所以没有办法“强制”任何东西。

根据您希望在测试中实现的目标,可能会有不同的解决方案。

简单的解决方案可以是在您的 junit 测试中使用真正的缓存,或者始终对实际存储进行读写的虚拟(非模拟)缓存。

【讨论】:

    猜你喜欢
    • 2012-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多