运行 使用 RabbitMQ 的 LatchCountDownAndCallRealMethodAnswer 进行测试时出现断言错误

Assertion error while running test with LatchCountDownAndCallRealMethodAnswer from RabbitMQ

我有一个侦听器测试,其中我 post 并行线程中的一条消息,并检查 LatchCountDownAndCallRealMethodAnswer 是否已成功处理所有消息。 运行 单独测试,它工作得很好,但是如果你 运行 所有其他测试一起,它会失败,因为它未能将计数器保持为零,但侦听器正常接收和处理消息。有人有什么想法吗?

我的测试Class

@RunWith(SpringRunner.class)
@SpringBootTest
@RabbitListenerTest
@ActiveProfiles("test")
public class EventListenerTest {

    EventListener eventListener;

    @Autowired
    protected RabbitListenerTestHarness harness;

    @Autowired
    private EventStoreRepository repository;

    @SpyBean
    private DomainEventPublisher publisher;

    @Before
    public void setUp() {
        MockitoAnnotations.initMocks(this);
        DomainRegister.setDomainEventPublisher(publisher);
        eventListener = this.harness.getSpy("eventListenerId");
    }

    @Test
    public void storeEventsListenerTest() throws Exception {

        LatchCountDownAndCallRealMethodAnswer answer = new LatchCountDownAndCallRealMethodAnswer(1);
        doAnswer(answer).when(eventListener).storeEvents(any(BalanceReserved.class));

        publisher.publish(new BalanceReserved("12233", 150.0, BigDecimal.ZERO), "");

        assertTrue(answer.getLatch().await(10, TimeUnit.SECONDS));

        verify(eventListener, times(1)).storeEvents(any(BalanceReserved.class));
    }

    @After
    public void tearDown() {
        DomainRegister.setDomainEventPublisher(null);
        reset(eventListener);
        repository.deleteAll();
    }

}

错误

java.lang.AssertionError

如果您有其他测试使用同一队列,则需要关闭每个测试的应用程序上下文,以便停止测试的侦听器。默认情况下,Spring 测试框架会缓存应用程序上下文以供重用。这将导致其他测试 "steal" 消息。

@DirtiesContext 添加到每个使用 @RabbitListener 的测试 class,以告诉测试框架关闭上下文。