如何在 JUnit 测试中强制执行模拟自动装配字段的重写方法?

How to force execution of overriden method of a mocked autowired field in JUnit tests?

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

// CacheInterceptor.java
public class CacheInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    private Cache<String, String> myCache;

    ...
}

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

// 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 class,我在其中模拟 myCache,因为在某些情况下我需要强制返回值。

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

public class CacheInterceptorTest {

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

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

的原始实现

我怎样才能做到这一点?

mock是一个独立的实现,它没有被覆盖的方法,所以没办法"force"什么

根据您希望在测试中实现的目标,可以采用不同的解决方案。

简单的解决方案可以是在您的 junit 测试中使用真实缓存,或者始终 reads-writes 到真实存储的虚拟(非模拟)缓存。