| 
  • If you are citizen of an European Union member nation, you may not use this service unless you are at least 16 years old.

  • You already know Dokkio is an AI-powered assistant to organize & manage your digital files & messages. Very soon, Dokkio will support Outlook as well as One Drive. Check it out today!

View
 

Unit testing concurrent access of static methods

Page history last edited by Manuel Kueblboeck 14 years, 6 months ago

Objects used in static methods have to be created within the control flow of the same method after the invocation of the method. Otherwise you risk running into race conditions where several threads modify the same object used by the static method. To test this you can do the following.

 

  • Write a test case for the static method in your unit test class

 

        private void testMyStaticMethod(Object parameter) {
                ClassUnderTest.myStaticMethod(parameter);
                assertTrue(<something>);
        }


  • Create a client class that runs this test within your unit test class

 

        private class MyStaticMethodClient extends Thread {
	       
	       private final Object parameter;
	       
	       public MyStaticMethodClient(String parameter) {
	               this.parameter = parameter;
	       }
	       
	       public void run() {
	               try {
	                       testMyStaticMethod(parameter);
	               } catch (Throwable t) {
                               // just calling the fail() method here is not enough because this is executed in another thread
	                      concurrencyError = t;
                       }
	       }
	}


  • Store the state of the test in a member variable within your unit test class

 

        private Throwable concurrencyError = null;


  • Call the static method concurrently from your unit test class

 

        @Test
	public void testMyStaticMethodConcurrently() {
	       for (int i = 1; i < 10; i++) {
	               if (concurrencyError != null) break;
	               MyStaticMethodClient clientA = new MyStaticMethodClient(TEST_PARAMETER);
	               MyStaticMethodClient clientB = new MyStaticMethodClient(TEST_PARAMETER);
	               clientA.start();
	               clientB.start();
	               try {
	                       clientA.join();
	                       clientB.join();
	               } catch (InterruptedException e) {
	                       fail(e.getMessage());
	               }
	               
	       }
	       assertNull("Concurrently executing the tested method failed with " + concurrencyError, concurrencyError);
	}

Comments (0)

You don't have permission to comment on this page.