001--【测试】并发测试类编写

1、写作背景

项目一定不仅仅是CRUD,更多的工作应该是放在测试,性能,稳定上面


2、参考网址

  • Java并发之CountDownLatch、Semaphore和CyclicBarrier:https://www.jianshu.com/p/bb5105303d85

3、进行工具类编写

项目功能编写完成之后,写测试用例,进行性能测试(很有必要)

@RunWith(SpringRunner.class)
@SpringBootTest
public class SeckillApplicationTests {

    public static final String SKU = "iPhone7";
    public static int UserCount = 5;
    public static int UserBuyCount = 3;
    public static AtomicInteger userSuccessCount = new AtomicInteger();
    public static AtomicInteger stackSuccessCount = new AtomicInteger();

    @Resource
    KillService killService;
    @Test
    public void contextLoads() {
        boolean flag = killService.updateGoodsCount(1, SKU);
        System.out.println("------------------数据更新成功:"+flag);
    }

    @Test
    // thread.join()等待线程组执行结束
    public void contextLoadsThread() throws InterruptedException {
        for (int i = 0; i < UserCount; i++) {
            Thread task = new Thread() {
                @Override
                public void run() {
                    doSomeThing();
                }
            };
            task.start();
            task.join();
        }
        System.out.println("------------------购买成功人数:"+userSuccessCount);
        System.out.println("------------------购买成功商品:"+stackSuccessCount);
    }

    // 核心业务操作
    public void doSomeThing() {
        if (killService.updateGoodsCount(UserBuyCount, SKU)){
            System.out.println("------------------数据更新成功");
            userSuccessCount.incrementAndGet();//购买成功用户加一
            stackSuccessCount.addAndGet(UserBuyCount);//购买成功商品
        }else {
            System.out.println("------------------数据更新失败");
        }
    }
}
  • 测试类编写最好避免以下:CountDownLatch、Semaphore和CyclicBarrier(因为没有办法判断当前线程是否已经完成任务处理)
    public void contextLoadsThread() throws Exception {
        ExecutorService executorService = Executors.newCachedThreadPool();
//        final Semaphore semaphore = new Semaphore(UserCount);
        final CountDownLatch countDownLatch = new CountDownLatch(UserCount);
        for (int i = 0; i < UserCount ; i++) {
            executorService.execute(() -> {
                try {
//                    semaphore.acquire();
                    doSomeThing();
//                    semaphore.release();
                } catch (Exception e) {
                    System.out.println("exception:"+e);
                }
                countDownLatch.countDown();
            });
        }
//        countDownLatch.await();
        executorService.shutdown();
        // 要稍微等一下,线程可能没有执行完成(没有接收异步任务)
        Thread.sleep(1000);
        System.out.println("-------------->任务执行完成");
    }

你可能感兴趣的:(001--【测试】并发测试类编写)