Никаких дальнейших запросов не ожидается, пока MockRestServiceServer был установлен в ExpectedCount.manyTimes()

У меня есть следующий тестовый класс для моего приложения для весенней интеграции, которое успешно запускается в одиночку

@SpringBootTest(classes = {BackupTestDefinition.class})
@ActiveProfiles({"test", "dev"})
@RunWith(SpringRunner.class)
public class BackupServiceTest {
    @Value(value = "${ne.endpoint}")
    private String ne;
    @Autowired
    private RestTemplate restTemplate;    
    private MockRestServiceServer mockServer;

    @Before
    public void setup() {
        mockServer = MockRestServiceServer.bindTo(restTemplate).build(new UnorderedRequestExpectationManager());
        mockServer.expect(ExpectedCount.manyTimes(), requestTo(UriComponentsBuilder.fromHttpUrl(ne).build().toUri())).andExpect(method(HttpMethod.POST)).andRespond(withSuccess());
    }

    @Test
    public void testNotificationProcessing() throws IOException, InterruptedException, InitializationException, ExecutionException {
        //some testing code
    }
}

Но у меня есть другой тест, который имеет другие параметры (ExpectedCount.times(1)) для той же конечной точки и имеет другое TestDefinition. Таким образом, в этом наборе тестов есть пара контекстов. И когда я запускаю их вместе, я получаю следующее исключение

at org.springframework.test.web.client.AbstractRequestExpectationManager.createUnexpectedRequestError(AbstractRequestExpectationManager.java:141)
at org.springframework.test.web.client.UnorderedRequestExpectationManager.validateRequestInternal(UnorderedRequestExpectationManager.java:49)
at org.springframework.test.web.client.AbstractRequestExpectationManager.validateRequest(AbstractRequestExpectationManager.java:76)
at org.springframework.test.web.client.MockRestServiceServer$MockClientHttpRequestFactory$1.executeInternal(MockRestServiceServer.java:289)
at org.springframework.mock.http.client.MockClientHttpRequest.execute(MockClientHttpRequest.java:94)
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:659)
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:620)
at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:538)
Caused by: java.lang.AssertionError: No further requests expected: HTTP POST

После нескольких часов отладки я обнаружил, что настройки были успешно применены, но похоже, что restTemplate был вызван из другого контекста, где количество попыток было исчерпано. Не могли бы вы помочь мне узнать, как решить эту проблему?

1 ответ

Решение

Эта проблема может быть решена с помощью @DirtiesContext на тестовом классе, наряду с @RunWith:

 * Test annotation which indicates that the
 * {@link org.springframework.context.ApplicationContext ApplicationContext}
 * associated with a test is <em>dirty</em> and should therefore be closed
 * and removed from the context cache.
 *
 * <p>Use this annotation if a test has modified the context &mdash; for
 * example, by modifying the state of a singleton bean, modifying the state
 * of an embedded database, etc. Subsequent tests that request the same
 * context will be supplied a new context.
 *
 * <p>{@code @DirtiesContext} may be used as a class-level and method-level
 * annotation within the same class or class hierarchy. In such scenarios, the
 * {@code ApplicationContext} will be marked as <em>dirty</em> before or
 * after any such annotated method as well as before or after the current test
 * class, depending on the configured {@link #methodMode} and {@link #classMode}.
 *

И вот документы по этому вопросу: https://docs.spring.io/spring/docs/5.0.6.RELEASE/spring-framework-reference/testing.html

Другие вопросы по тегам