How to unit test a synchronous method in java?

允我心安 提交于 2019-12-11 13:12:55

问题


I am curious to know how to unit test a synchronous method in Java. Can we use mocking frameworks like 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

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

Thanks,
Cot


回答1:


I am curious to know how to unit test a synchronous method in 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. 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.



来源:https://stackoverflow.com/questions/18839327/how-to-unit-test-a-synchronous-method-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!