JUnit测试Spring @Async void服务方法

我有一个春季服务:

@Service

@Transactional

public class SomeService {

@Async

public void asyncMethod(Foo foo) {

// processing takes significant time

}

}

我为此进行了集成测试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.

}

这是问题所在:

  • 正如SomeService.asyncMethod(..)@Async和注释的
  • 因为SpringJUnit4ClassRunner坚持@Async语义

testAsyncMethod线程将呼叫分叉someService.asyncMethod(testData)到自己的工作线程,然后直接继续执行verifyResults(),以前的工作线程完成其工作可能之前。

如何someService.asyncMethod(testData)在验证结果之前等待的完成?注意,如何使用Spring4和批注编写单元测试以验证异步行为_ 的解决方案?不要在这里申请,作为someService.asyncMethod(testData)回报void,而不是Future<?>

回答:

为了@Async遵守语义,某些活动@Configuration类将具有@EnableAsync注释,例如

@Configuration

@EnableAsync

@EnableScheduling

public class AsyncConfiguration implements AsyncConfigurer {

//

}

为了解决我的问题,我引入了一个新的Spring配置文件non-async

如果non-async配置文件 激活,AsyncConfiguration则使用:

@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

}

如果非异步轮廓 活动的,则NonAsyncConfiguration使用:

@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

}

现在,在有问题的JUnit测试类中,我显式激活“非异步”概要文件,以相互排除异步行为:

@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.

}

以上是 JUnit测试Spring @Async void服务方法 的全部内容, 来源链接: utcz.com/qa/420436.html

回到顶部