栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

【无标题】

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

【无标题】

记一次单元测试的坑

借鉴了这个大佬的文章junit进行单元测试
先说结论:junit进行单元测试的时候执行结束会调用system.exit()方法,所以这里不适合进行多线程测试。

@Configuration
@SpringBootTest(classes = RedisApplication.class)
public class test {
    
    @Autowired
    StringRedisTemplate redisTemplate;

    @Bean
    ValueOperations valueOperations(){
        return redisTemplate.opsForValue();
    }

    class MyThread implements ThreadFactory{
        @Override
        public Thread newThread(Runnable r) {
            Thread thread = new Thread(r);
            thread.setDaemon(false);
            return thread;
        }
    }
    
    
    @Bean
    ExecutorService executors(){
        return Executors.newFixedThreadPool(10,new MyThread());
    }

    
    class Task implements Runnable{
        @Override
        public void run() {
            while(!redisTemplate.opsForValue().setIfAbsent("first","number")){
                System.out.println("try to get lockt"+Thread.currentThread().getName());
                try {
                    TimeUnit.SECONDS.sleep(3);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println("get lock exec service:"+Thread.currentThread().getName());
            valueOperations().getAndExpire("first", Duration.ofSeconds(3));
        }
    }

    @Test
    public void zz() throws InterruptedException {
        executors().execute(new Task());
        executors().execute(new Task());
        executors().execute(new Task());
        executors().execute(new Task());
        executors().execute(new Task());
        executors().execute(new Task());
    }
}

上述代码模拟了分布式锁的场景,但是测试的时候发现没有任何打印信息。问题如上述结论一样。
这里正确的执行可以在测试方法中使用死循环保证我们的主程序不被退出。从而导致其他线程可以正确执行。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1032803.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号