Исключение одновременной модификации Maven Surefire

Когда Maven строит мой проект и запускает модульные тесты, иногда возникает исключение одновременной модификации (примерно в 1 из 5 раз он завершится ошибкой, в других случаях он будет успешно построен). Но когда я запускаю тесты локально как модульные, все без исключения проходят успешно.

В моем файле pom.xml у меня есть плагин Surefire, настроенный как:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>2.19.1</version>
    <configuration>
        <forkCount>1C</forkCount>
        <reuseForks>true</reuseForks>
    </configuration>
    <dependencies>
        <dependency>
              <groupId>org.apache.maven.surefire</groupId>
              <artifactId>surefire-junit47</artifactId>
              <version>2.19.1</version>
        </dependency>
    </dependencies>
</plugin>

Однако в stacktrace, который я возвращаю, не упоминается, что вызывает исключение одновременной модификации.

Я заметил, что все тесты проходят сборку, но по какой-то причине Maven перепечатывает результат теста, который уже прошел, но теперь имеет тестовое исключение ConcurrentModification.

Я не уверен, что вызывает повторную печать результата теста или по какой-то причине тест повторяется одновременно с тем, что первый запуск теста не был завершен, поскольку это параллельная сборка? (Не уверен, зачем нужно было повторно запускать тест)

Трассировки стека

[Test executing]

13:48:24.869 [00001-main] DEBUG o.s.t.c.s.DirtiesContextTestExecutionListener - After test method: context [DefaultTestContext@375046d6 testClass = Tests, testInstance = com.application.Tests@179181c, testMethod = failingTest@Tests, testException = [null], mergedContextConfiguration = [WebMergedContextConfiguration@3f7b4a61 testClass = Tests, locations = '{}', classes = '{class com.Application}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{}', resourceBasePath = 'src/main/app', contextLoader = 'org.springframework.test.context.web.WebDelegatingSmartContextLoader', parent = [null]]], class dirties context [false], class mode [null], method dirties context [false].
13:48:24.869 [00001-main] DEBUG o.s.t.c.w.ServletTestExecutionListener - Resetting RequestContextHolder for test context [DefaultTestContext@375046d6 testClass = Tests, testInstance = com.application.Tests@179181c, testMethod = failingTest@Tests, testException = [null], mergedContextConfiguration = [WebMergedContextConfiguration@3f7b4a61 testClass = Test, locations = '{}', classes = '{class com.Application}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{}', resourceBasePath = 'src/main/app', contextLoader = 'org.springframework.test.context.web.WebDelegatingSmartContextLoader', parent = [null]]].

[Some other tests executing]

13:48:28.632 [00001-main] DEBUG o.s.t.c.s.DirtiesContextTestExecutionListener - After test method: context [DefaultTestContext@54fde1bc testClass = Tests, testInstance = com.application.Tests@57ffa818, testMethod = failingTest@Tests, testException = java.util.ConcurrentModificationException, mergedContextConfiguration = [WebMergedContextConfiguration@5247834f testClass = Tests, locations = '{}', classes = '{class com.Application}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{}', resourceBasePath = 'src/main/app', contextLoader = 'org.springframework.test.context.web.WebDelegatingSmartContextLoader', parent = [null]]], class dirties context [false], class mode [null], method dirties context [false].
13:48:28.632 [00001-main] DEBUG o.s.t.c.w.ServletTestExecutionListener - Resetting RequestContextHolder for test context [DefaultTestContext@54fde1bc testClass = Tests, testInstance = com.application.Tests@57ffa818, testMethod = failingTest@Tests, testException = java.util.ConcurrentModificationException, mergedContextConfiguration = [WebMergedContextConfiguration@5247834f testClass = Tests, locations = '{}', classes = '{class com.Application}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{}', resourceBasePath = 'src/main/app', contextLoader = 'org.springframework.test.context.web.WebDelegatingSmartContextLoader', parent = [null]]].
failingTest(com.application.Tests)  Time elapsed: 0 sec  <<< ERROR!
java.util.ConcurrentModificationException

[Some other tests executing]

Results :

Tests in error: 
  Tests.failingTest» ConcurrentModification

Я не уверен, что вызывает исключение одновременной модификации или как избежать этой проблемы, поскольку это случается только иногда, но это тот же тест, который терпит неудачу, а не другие тесты в моем наборе тестов.


person diepjy    schedule 21.11.2016    source источник
comment
Может быть, потому что ваши тесты нельзя запускать параллельно и разделять какое-то состояние? Вы можете им показать? Можете ли вы также опубликовать полную трассировку стека?   -  person Tunaki    schedule 21.11.2016
comment
Я проверил, что тестируемый код не имеет никакого состояния. Трассировка стека - это просто успешно запущенный тест, за которым следуют другие тесты. Но нигде в stacktrace не упоминается исключение одновременной модификации, кроме того, что я включил в stacktrace, поэтому я не знаю, откуда оно будет   -  person diepjy    schedule 21.11.2016
comment
Полная трассировка стека находится не в консоли, а в файле отчетов. Если хотите, чтобы это было в консоли, сделайте mvn -Dsurefire.useFile=false test.   -  person Tunaki    schedule 21.11.2016
comment
Я запустил сборку Maven с трассировкой стека, но с тем же выводом трассировки стека. Единственная трассировка стека, которую я получаю, - это та, которую я ожидаю от теста (без исключения одновременной модификации), но нет трассировки стека, когда возникает исключение одновременной модификации, только трассировка стека других выполненных тестов.   -  person diepjy    schedule 21.11.2016
comment
Возможно, ваш код неправильно регистрирует ошибку.   -  person Tunaki    schedule 21.11.2016
comment
У меня точно такая же проблема после обновления до версии 2.19.1. Я использую TestNG для модульных тестов и Jacoco для покрытия.   -  person Jagger    schedule 06.12.2016


Ответы (2)


Я обнаружил, что проблема возникла из-за метода, который я не смоделировал, который создавал и запускал поток (даже если поток не изменял какие-либо ресурсы), поэтому я высмеял его, и проблема, похоже, решена.

person diepjy    schedule 06.12.2016

У меня была такая же проблема, но она была связана с изменением, внесенным в Collections.sort () в Java 8. Дополнительная информация.

person Paulo Merson    schedule 31.05.2017