texpert
texpert

Reputation: 215

How to unit test a synchronous method in java?

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

Upvotes: 1

Views: 4787

Answers (1)

Gray
Gray

Reputation: 116908

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.

Upvotes: 1

Related Questions