JUnit test d'un Printemps @Async void méthode de service

J'ai un Ressort de service:

@Service
@Transactional
public class SomeService {

    @Async
    public void asyncMethod(Foo foo) {
        //processing takes significant time
    }
}

Et j'ai un test d'intégration pour cette SomeService:

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Application.class)
@WebAppConfiguration
@IntegrationTest
@Transactional
public class SomeServiceIntTest {

    @Inject
    private SomeService someService;

        @Test
        public void testAsyncMethod() {

            Foo testData = prepareTestData();

            someService.asyncMethod(testData);

            verifyResults();
        }

        //verifyResult() with assertions, etc.
}

Voici le problème:

  • comme SomeService.asyncMethod(..) est annoté avec @Async et
  • comme le SpringJUnit4ClassRunner adhère à la @Async sémantique

la testAsyncMethod fil de la fourche à l'appel someService.asyncMethod(testData) dans son propre thread de travail, puis directement à poursuivre l'exécution de verifyResults(), peut-être avant le précédent thread de travail a achevé ses travaux.

Comment puis-je attendre pour someService.asyncMethod(testData)'achèvement avant de vérifier les résultats? Notez que les solutions à Comment puis-je écrire un test unitaire pour vérifier async comportement à l'aide de Printemps 4 et annotations? ne s'appliquent pas ici, comme someService.asyncMethod(testData) retourne void, pas un Future<?>.

OriginalL'auteur Abdull | 2017-02-24