Test Coverage for a Void Method

I ran across some state code that had plugs in it that were operations an action listener would look for.  The code methods didn’t have anything in them, but needed to be there.  I wanted some simple unit testing coverage on them.  Here’s a small technique to cover a void method that doesn’t do too much.

Here’s the code to be tested. Notice I made 2 methods for my tests, one throws an error. I’ve included to ways of testing for errors in the attached repository code.


public class TestClassImpl implements TestClass {
   public void methodNoError() {}
   public void methodError() {throw new RuntimeException();}	
}

 

To test methodNoError, we just use a Boolean and flag it if there is an error, and assert that variable. The other two tets are separate ways to check methodError() which actually throws an error.


@Test
public void testMethodNoError() {	
   Boolean testState = true;	
   try {	
      testClass.methodNoError();	
   } catch (Exception e) {
      testState = false;
   }		
   assertTrue(testState);
}
	
@Test
public void testMethodError() {	
   Boolean testState = true;
   try {	
      testClass.methodError();	
   } catch (Exception e) {
      testState = false;
   }	
   assertFalse(testState);
}
	
@Test(expected = Exception.class)
public void testMethodErrorExpected() {testClass.methodError();}

 

You can try this out with the TestVoid project folder in my Bitbucket; just run “mvn clean install” or load it into your IDE.

TestVoid

, ,

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>