Spring-test:集成测试中,单元测试上下文相互干扰问题的排查

运行环境:
jdk1.8 junit spring-test

一、背景

最近公司的项目的集成测试遇到一个问题,单元测试方法中,用Mockito.verify对依赖服务进行Mockito.times()调用次数验证时,总是处于不稳定的状态,偶尔会出现不符合预期的情况。验证的情况如下:

Mockito.verify(testService, Mockito.times(1)).printHelloWord();

这里对出现问题的程序现状做个说明:
1.1 集成测试插件的配置情况:

 <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-surefire-plugin</artifactId>
        <version>2.22.1</version>
        <configuration>
          <forkCount>4</forkCount>
        </configuration>
</plugin>

1.2 依赖服务类ITestService如下:

public interface ITestService {
   
    String printHelloWord();
}

1.3 mock的bean配置服务如下所示:

@Configuration
public class CreateBeanFactory {
   
    private  final Logger logger = LoggerFactory.getLogger(CreateBeanFactory.class);
    
    @Bean
    public ITestService createTestService() {
   
        ITestService testService = Mockito.mock(ITestService.class);
        logger.info("线程:{}, hashcode:{}", Thread.currentThread().getName(), testService.hashCode());
        return testService;
    }

1.4 集成测试的抽象服务类如下:

RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {
   "classpath*:spring-*.xml" })
public class SpringBaseServiceTest {
   
    @Resource
    private ITestService testService;
    
	@After
	public void clearContext() {
   
	   // 执行完单测后对单测依赖的mock服务进行重置
	   Mockito.reset(testService);
	}
}

1.5 单测类Test1如下:

public class Test1 extends SpringBaseServiceTest {
   
    private  final Logger logger = LoggerFactory.getLogger(Test1.class);
    
    @Resource
    private ITestService testService;

    @Test
    public void testPrintStopWord() {
   
        Mockito.when(testService.printHelloWord()).thenReturn("Test1 stop word");
        logger.info("test1 print:{}", testService.printHelloWord());
        Mockito.verify(testService, Mockito.times(1)).printHelloWord();
    }

    @Test
    public void testPrintHelloWord() {
   
        Mockito.when(testService.printHelloWord()).thenReturn("Test1 Hello word");
        logger.info("test1 print:{}", testService.printHelloWord());
        Mockito.verify(testService, Mockito.times(1)).printHelloWord();
    }
}

1.6 单测类Test2如下:

public class Test2 extends SpringBaseServiceTest {
   
    private  final Logger logger = LoggerFactory.getLogger(Test2.class);
    //记录定时任务执行几次了
    private static int count = 0;
    private ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(5);
    
    @Resource
    private ITestService testService;
    
    @Test
    public void testPrintBaby() {
   
        Mockito.when(testService.printHelloWord
  • 12
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值