简体   繁体   English

如何在Java中对同步方法进行单元测试?

[英]How to unit test a synchronous method in java?

I am curious to know how to unit test a synchronous method in Java. 我很好奇知道如何在Java中对同步方法进行单元测试。 Can we use mocking frameworks like jMockit, Mockito? 我们可以使用jMockit,Mockito等模拟框架吗?

I am looking for an answer for something similar to an interesting post at : http://www.boards.ie/vbulletin/showthread.php?t=2056674659 我正在寻找类似于以下有趣帖子的答案: http : //www.boards.ie/vbulletin/showthread.php?t=2056674659

Unfortunately, instead of suggestions/answer, there were unnecesary discussions ! 不幸的是,没有建议/答案,而是不必要的讨论!

Thanks, 谢谢,
Cot 婴儿床

I am curious to know how to unit test a synchronous method in Java. 我很好奇知道如何在Java中对同步方法进行单元测试。

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. 你当然可以写一个使用数量一直在呼唤的方法和测试任何线程的测试synchronized关键字保护。 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. 尽管良好的单元测试覆盖范围几乎总是一件好事,但使用线程编程恕我直言,更有用的是与另一位知识渊博的开发人员对互斥体和方法中及其周围的数据共享进行良好的配对编程审查。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM