当前位置: 首页 > 知识库问答 >
问题:

加载缓存实现的单元测试单独通过,但一个在一起运行时失败

郑嘉悦
2023-03-14

我为咖啡因CacheLoader实现编写的单元测试(JUnit,Mockito)在单独运行时都成功了,但在一起运行时其中一个失败了。我相信我在所有测试对象设置中使用了@之前的最佳实践。

当与其他人一起运行时,测试testGet_WhenCalledASecondAndThirdTimeBeyondCacheDuration_LoadingMethodCalledASecondTime每次都会失败,并出现以下错误:

org.mockito.exceptions.verification.TooLittleActualInvocations: 
testDataSource.getObjectWithKey(
    "mountain-bikes"
);
Wanted 2 times:
-> at ErrorHandlingLoadingCacheFactoryTest.testGet_WhenCalledASecondAndThirdTimeBeyondCacheDuration_LoadingMethodCalledASecondTime(ErrorHandlingLoadingCacheFactoryTest.java:67)
But was 1 time:
-> at ErrorHandlingCacheLoader.load(ErrorHandlingCacheLoader.java:41)

在两次测试之间似乎有什么东西在继续,但考虑到我在@Before方法中所做的,我不确定这是怎么回事。我已尝试在@After方法中调用以下内容:

  • invalidateAll()

我还尝试手动将一个unileThreadExecator传递给缓存生成器,并等待它在@After中完成它正在做的任何事情,以防与它有关。

如果刷新当前缓存值的尝试失败(引发异常),我的CacheLoader实现将覆盖reload方法以返回当前缓存的值。除此之外,它是相当香草的。

@Component
public class ErrorHandlingLoadingCacheFactory {

    private final Ticker ticker;

    @Autowired
    public ErrorHandlingLoadingCacheFactory(Ticker ticker) {
        this.ticker = ticker;
    }

    public <T> LoadingCache<String, T> buildCache(String cacheName,
                                                        long duration,
                                                        TimeUnit timeUnit,
                                                        Function<String, T> valueResolver) {
        return Caffeine.newBuilder()
                .refreshAfterWrite(duration, timeUnit)
                .ticker(ticker)
                .build(new ErrorHandlingCacheLoader<>(cacheName, valueResolver));
    }
}
/**
 *  a LoadingCache that retains stale cache values if
 *  an attempt to retrieve a fresh value for a given key fails.
 *
 * @param <K> the cache key type
 * @param <V> the cache value type
 */
class ErrorHandlingCacheLoader<K, V> implements CacheLoader<K, V> {
    private final static Logger logger = LoggerFactory.getLogger(ErrorHandlingCacheLoader.class);

    private final String cacheName;
    private final Function<K, V> valueResolver;

    /**
     * Create a cache.
     *
     * @param cacheName the cache name
     * @param valueResolver the method used to get a value for a key
     */
    public ErrorHandlingCacheLoader(String cacheName, Function<K, V> valueResolver) {
        this.cacheName = cacheName;
        this.valueResolver = valueResolver;
    }

    /**
     * Load the initial cache value for a given key.
     * @param key the cache key
     * @return the initial value to cache
     */
    @Override
    public V load(@NonNull K key) {
        return valueResolver.apply(key);
    }

    /**
     * Attempt to reload a value for a given key.
     * @param key the cache key
     * @param oldValue the currently cached value for the given key
     * @return
     */
    @Override
    public V reload(@NonNull K key, V oldValue) {
        V value = oldValue;
        try {
            value = valueResolver.apply(key);
        } catch (RuntimeException e) {
            logger.warn("Failed to retrieve value for key '{}' in cache '{}'. Returning currently cached value '{}'.", key, cacheName, oldValue);
        }
        return value;
    }
}
public class ErrorHandlingLoadingCacheFactoryTest {

    private ErrorHandlingLoadingCacheFactory errorHandlingLoadingCacheFactory;

    private FakeTicker fakeTicker;
    private TestDataSource testDataSource;

    private LoadingCache<String, TestObject> loadingCache;

    @Before
    public void setUp() {
        fakeTicker = new FakeTicker();
        testDataSource = mock(TestDataSource.class);
        errorHandlingLoadingCacheFactory = new ErrorHandlingLoadingCacheFactory(fakeTicker::read);
        loadingCache = errorHandlingLoadingCacheFactory.buildCache("testCache", 1, TimeUnit.HOURS, testDataSource::getObjectWithKey);
    }

    @After
    public void tearDown() {
        validateMockitoUsage();
    }

    @Test
    public void testGet_WhenCalledTwiceWithinCachePeriod_LoadingMethodCalledOnce() {
        // Arrange
        TestObject testObject = new TestObject("Mountain Bikes");
        when(testDataSource.getObjectWithKey("mountain-bikes")).thenReturn(testObject);

        // Act
        TestObject result1 = loadingCache.get("mountain-bikes");
        TestObject result2 = loadingCache.get("mountain-bikes");

        // Assert
        verify(testDataSource, times(1)).getObjectWithKey("mountain-bikes");
        assertThat(result1).isEqualTo(testObject);
        assertThat(result2).isEqualTo(testObject);
    }

    @Test
    public void testGet_WhenCalledASecondAndThirdTimeBeyondCacheDuration_LoadingMethodCalledASecondTime() {
        // Arrange
        TestObject testObject1 = new TestObject("Mountain Bikes 1");
        TestObject testObject2 = new TestObject("Mountain Bikes 2");
        when(testDataSource.getObjectWithKey("mountain-bikes")).thenReturn(testObject1, testObject2);

        // Act
        TestObject result1 = loadingCache.get("mountain-bikes");
        fakeTicker.advance(2, TimeUnit.HOURS);
        TestObject result2 = loadingCache.get("mountain-bikes");
        TestObject result3 = loadingCache.get("mountain-bikes");

        // Assert
        verify(testDataSource, times(2)).getObjectWithKey("mountain-bikes");
        assertThat(result1).isEqualTo(testObject1);
        assertThat(result2).isEqualTo(testObject1);
        assertThat(result3).isEqualTo(testObject2);
    }

    @Test(expected = RuntimeException.class)
    public void testGet_WhenFirstLoadCallThrowsRuntimeException_ThrowsRuntimeException() {
        // Arrange
        when(testDataSource.getObjectWithKey("mountain-bikes")).thenThrow(new RuntimeException());

        // Act
        loadingCache.get("mountain-bikes");
    }

    @Test
    public void testGet_WhenFirstLoadCallSuccessfulButSecondThrowsRuntimeException_ReturnsCachedValueFromFirstCall() {
        // Arrange
        TestObject testObject1 = new TestObject("Mountain Bikes 1");
        when(testDataSource.getObjectWithKey("mountain-bikes")).thenReturn(testObject1).thenThrow(new RuntimeException());

        // Act
        TestObject result1 = loadingCache.get("mountain-bikes");
        fakeTicker.advance(2, TimeUnit.HOURS);
        TestObject result2 = loadingCache.get("mountain-bikes");

        // Assert
        verify(testDataSource, times(2)).getObjectWithKey("mountain-bikes");
        assertThat(result1).isEqualTo(testObject1);
        assertThat(result2).isEqualTo(testObject1);
    }

    @Test
    public void testGet_WhenFirstLoadCallSuccessfulButSecondThrowsRuntimeException_SubsequentGetsReturnCachedValueFromFirstCall() {
        // Arrange
        TestObject testObject1 = new TestObject("Mountain Bikes 1");
        when(testDataSource.getObjectWithKey("mountain-bikes")).thenReturn(testObject1).thenThrow(new RuntimeException());

        // Act
        TestObject result1 = loadingCache.get("mountain-bikes");
        fakeTicker.advance(2, TimeUnit.HOURS);
        TestObject result2 = loadingCache.get("mountain-bikes");
        TestObject result3 = loadingCache.get("mountain-bikes");

        // Assert
        verify(testDataSource, times(2)).getObjectWithKey("mountain-bikes");
        assertThat(result1).isEqualTo(testObject1);
        assertThat(result2).isEqualTo(testObject1);
        assertThat(result3).isEqualTo(testObject1);
    }

    @Test(expected = NullPointerException.class)
    public void testGet_WhenKeyIsNull_ThrowsNullPointerException() {
        // Arrange
        String key = null;

        // Act
        loadingCache.get(key);
    }

    @Test
    public void testGet_WhenFirstLoadCallReturnsNull_DoesNotCacheResult() {
        // Arrange
        TestObject testObject1 = new TestObject("Mountain Bikes 1");
        when(testDataSource.getObjectWithKey("mountain-bikes")).thenReturn(null).thenReturn(testObject1);

        // Act
        TestObject result1 = loadingCache.get("mountain-bikes");
        TestObject result2 = loadingCache.get("mountain-bikes");

        // Assert
        verify(testDataSource, times(2)).getObjectWithKey("mountain-bikes");
        assertThat(result1).isEqualTo(null);
        assertThat(result2).isEqualTo(testObject1);
    }

    @Data
    class TestObject {
        private String id;
        public TestObject(String id) {
            this.id = id;
        }
    }

    interface TestDataSource {
        TestObject getObjectWithKey(String key);
    }
}

共有1个答案

扶冠宇
2023-03-14

Ben Manes在他的评论中建议我在运行单元测试时使用Runnable::run作为LoadingCache的执行器,这就成功了!

我在我的工厂上实现了第二个受保护的BuildCache方法,该方法另外需要一个Execator参数,我的测试类使用该参数传递Runnable::run

更新的ErrorHandlingLoadingCacheFactory:

public class ErrorHandlingLoadingCacheFactory {

    private final Ticker ticker;

    @Autowired
    public ErrorHandlingLoadingCacheFactory(Ticker ticker) {
        this.ticker = ticker;
    }

    /**
     * Create an in-memory LoadingCache
     *
     * @param cacheName the name of the cache
     * @param duration how long to keep values in the cache before attempting to refresh them
     * @param timeUnit the unit of time of the given duration
     * @param valueResolver the method to call to get a value to load into the cache for a given key
     * @param <T> the type of object to store into the cache
     * @return the newly created cache
     */
    public <T> LoadingCache<String, T> buildCache(String cacheName,
                                                        long duration,
                                                        TimeUnit timeUnit,
                                                        Function<String, T> valueResolver) {
        return buildCache(cacheName, duration, timeUnit, valueResolver, ForkJoinPool.commonPool());
    }

    /**
     * Create an in-memory LoadingCache
     *
     * @param cacheName the name of the cache
     * @param duration how long to keep values in the cache before attempting to refresh them
     * @param timeUnit the unit of time of the given duration
     * @param valueResolver the method to call to get a value to load into the cache for a given key
     * @param executor the executor for the cache to use
     * @param <T> the type of object to store into the cache
     * @return the newly created cache
     */
    protected <T> LoadingCache<String, T> buildCache(String cacheName,
                                                     long duration,
                                                     TimeUnit timeUnit,
                                                     Function<String, T> valueResolver,
                                                     Executor executor) {
        return Caffeine.newBuilder()
                .refreshAfterWrite(duration, timeUnit)
                .ticker(ticker)
                .executor(executor)
                .build(new ErrorHandlingCacheLoader<>(cacheName, valueResolver));
    }
}

ErrorHandlingLoadingCacheFactoryTest中更新的setUp()方法:

...
@Before
    public void setUp() {
        fakeTicker = new FakeTicker();
        testDataSource = mock(TestDataSource.class);
        errorHandlingLoadingCacheFactory = new ErrorHandlingLoadingCacheFactory(fakeTicker::read);
        loadingCache = errorHandlingLoadingCacheFactory.buildCache("testCache", 1, TimeUnit.HOURS, testDataSource::getObjectWithKey, Runnable::run);
    }
...

我的单线程执行器一定没有捕捉到测试之间的竞争,可能是因为我没有正确地等待它在我的@After方法中终止。Ben建议,如果我在单线程执行器上使用waitintetermination,这也可能有效。

 类似资料:
  • 我有一堆JUnit测试,它们都单独运行。每一个都是一个真正的独立单元测试--被测试的单个类。不需要上下文。我可以在Eclipse中或通过maven/surefire-plugin单独或一起运行它们。 此后,我添加了一个新的集成测试,它利用了Spring上下文等,并使用了SpringJUnit4ClassRunner。一旦我将这个测试添加到我的套件中,任何测试用例都会在这个类失败后运行。 我不确定这

  • 我目前正在做一个学校的作业,我正在努力与测试部分。出于某种原因,单元测试单独运行时运行良好,但一起运行时就不行了。我知道这与我在他们之间共享对象有关,而我不应该基于我以前的搜索,但我一生都无法找出需要改变什么来解决这个问题。下面是ApplientService类和ApplientServiceTest类的代码。任何帮助都将非常感谢,因为我已经被困在这个问题上一段时间了,现在知道这可能是其他人会立即

  • 这是我的整个测试课程: 有3个单元测试,它们在单独运行时都通过了,但当我运行整个测试类时,我的第2个和第3个测试失败,错误如下: 我已经想尽一切办法来解决这个问题: 我将测试实例化下的类移动到@Before函数中 我尝试创建@After函数并调用Mockito。重置我的模拟 我应该提到的是,我正在使用nhaarman。mockitokotlin2库和argumentCaptor。 关于为什么这些测

  • 不要与之前提出的问题混淆“为什么我的测试在一起运行时失败,但单独通过?” 我有一个任务,我需要修改JUnit测试类来处理多个数据库测试。在实现之前,我需要确保所有测试都在运行,没有失败。令我困惑的是,现在当我一起运行所有的类时,它显示它运行时没有失败。当我运行一个特定的类时,它突然失败了,如果我重复它,结果仍然存在。 这可能是什么原因造成的? 我自己没有写测试,因此我对测试内容的了解是有限的。不过

  • 我有几个JUnit测试,都使用运行。我可以从我的SpringSource工具套件(EclipseJuno)IDE中按类单独运行它们,它们通过了。如果我尝试按模块运行它们(“运行所选项目中的所有测试”),则它们将失败,并出现以下初始化错误: 有什么办法解决吗?甚至故障排除。 吉文斯: JUnit 4.11版

  • 我一直遇到一个奇怪的问题。我的测试用例有一个失败的测试,。但是,如果我单独运行相同的程序,它将运行得非常完美。我不熟悉JUnit,不知道为什么会发生这种情况。 如果我注释掉最后一个测试(已经注释掉),我的所有测试都成功运行!然而,如果我不评论它,一个测试失败,但那不是这个测试!它是失败!