JUnit-testing a Spring @Async void service method

后端 未结 4 1675
情话喂你
情话喂你 2020-12-29 03:15

I have a Spring service:

@Service
@Transactional
public class SomeService {

    @Async
    public void asyncMethod(Foo foo) {
        // processing takes si         


        
4条回答
  •  误落风尘
    2020-12-29 03:42

    For @Async semantics to be adhered, some active @Configuration class will have the @EnableAsync annotation, e.g.

    @Configuration
    @EnableAsync
    @EnableScheduling
    public class AsyncConfiguration implements AsyncConfigurer {
    
      //
    
    }
    

    To resolve my issue, I introduced a new Spring profile non-async.

    If the non-async profile is not active, the AsyncConfiguration is used:

    @Configuration
    @EnableAsync
    @EnableScheduling
    @Profile("!non-async")
    public class AsyncConfiguration implements AsyncConfigurer {
    
      // this configuration will be active as long as profile "non-async" is not (!) active
    
    }
    

    If the non-async profile is active, the NonAsyncConfiguration is used:

    @Configuration
    // notice the missing @EnableAsync annotation
    @EnableScheduling
    @Profile("non-async")
    public class NonAsyncConfiguration {
    
      // this configuration will be active as long as profile "non-async" is active
    
    }
    

    Now in the problematic JUnit test class, I explicitly activate the "non-async" profile in order to mutually exclude the async behavior:

    @RunWith(SpringJUnit4ClassRunner.class)
    @SpringApplicationConfiguration(classes = Application.class)
    @WebAppConfiguration
    @IntegrationTest
    @Transactional
    @ActiveProfiles(profiles = "non-async")
    public class SomeServiceIntTest {
    
        @Inject
        private SomeService someService;
    
            @Test
            public void testAsyncMethod() {
    
                Foo testData = prepareTestData();
    
                someService.asyncMethod(testData);
    
                verifyResults();
            }
    
            // verifyResult() with assertions, etc.
    }
    

提交回复
热议问题