如何在Java中对同步方法进行单元测试? [英] How to unit test a synchronous method in java?

查看:96
本文介绍了如何在Java中对同步方法进行单元测试?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很好奇知道如何在Java中对同步方法进行单元测试.我们可以使用诸如jMockit,Mockito之类的模拟框架吗?

I am curious to know how to unit test a synchronous method in Java. Can we use mocking frameworks like jMockit, Mockito?

我正在寻找类似于以下有趣帖子的答案: http ://www.boards.ie/vbulletin/showthread.php?t = 2056674659

I am looking for an answer for something similar to an interesting post at : http://www.boards.ie/vbulletin/showthread.php?t=2056674659

不幸的是,没有必要的讨论,没有建议/答案!

Unfortunately, instead of suggestions/answer, there were unnecesary discussions !

谢谢,
Cot

Thanks,
Cot

推荐答案

我很好奇知道如何在Java中对同步方法进行单元测试.

I am curious to know how to unit test a synchronous method in Java.

如果您的意思是如何编写单元测试以测试方法(或类)是否正确同步,则这是一项艰巨的任务.您当然可以编写一个使用多个线程的测试,这些线程不断调用该方法并测试synchronized关键字所保护的内容.但是,真正地测试围绕它的保护可能并不那么简单.

If you mean how to write a unit test to test whether a method (or class) is properly synchronized, this is a difficult task to accomplish. You can certainly write a test that uses a number of threads that keep calling the method and testing whatever the synchronized keyword is protecting. But truly testing the protections around it may not be as simple.

 public void testPummel() {
     ExecutorService fireHose = Executors.newFixedThreadPool(100);
     final Foo sharedInstance = new Foo();
     fireHose.submit(new Runnable() {
         public void run() {
             for (int i = 0; i < 100; i++) {
                 // setup test
                 Result result = sharedInstance.synchronizedMethodToTest(...);
                 // test result
             }
         }
     });
     fireHose.shutdown();
     fireHose.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS);
 }

尽管这在任何外部机制方面都做得很好,但它实际上永远无法保证对同步方法的多次调用,并且在没有造成破坏您应用程序时间的工具的情况下能够正确执行.

Although this does a good job as any external mechanism, it really can never guarantee that multiple calls to your synchronized method are being made and that it is being properly exercised without instrumentation that would destroy the timing of your application.

尽管良好的单元测试覆盖率始终是件好事,但线程编程恕我直言,更有用的是与另一位知识渊博的人对方法中及其周围的互斥量和数据共享进行良好的配对编程审查.开发人员.

Although good unit test coverage is just about always a good thing, what is more useful with threaded programming IMHO is good pair programming review of the mutex and data sharing in and around the method with another knowledgeable developer.

这篇关于如何在Java中对同步方法进行单元测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆