May, 2009 Archive

JUnit 4.7: Interceptors: expected exceptions

May 26th, 2009 by David Saff in Uncategorized

In the latest snapshot build of JUnit 4.7, we’ve re-implemented expected exceptions using Interceptors. Share and Enjoy!

	public static class HasExpectedException {
		@Interceptor
		public ExpectedException thrown= new ExpectedException();

		@Test
		public void throwsNothing() {

		}

		@Test
		public void throwsNullPointerException() {
			thrown.expect(NullPointerException.class);
			throw new NullPointerException();
		}

		@Test
		public void throwsNullPointerExceptionWithMessage() {
			thrown.expect(NullPointerException.class);
			thrown.expectMessage("happened?");
			throw new NullPointerException("What happened?");
		}
	}

Getting the name of the currently-running test method

May 11th, 2009 by David Saff in Uncategorized

One of the most common requests since JUnit 4.0 was released has been to restore a somewhat accidental feature of JUnit 3.8.  Since, in 3.8, the same object handled test execution and test lifetime management, a test method had access to the getName() method of TestCase, which was internally used for reporting.  Many extenders used this fact to build informed lightweight logging functions.  In JUnit 4.0, this accidental feature was not replicated, which made it difficult to port some of these logging routines.

In the latest snapshot of JUnit 4.7, we’ve re-introduced this feature, by way of Interceptors.  It looks like this:

    @RunWith(Interceptors.class)
    public class NameInterceptorTest {
        @Interceptor public TestName name = new TestName();

        @Test public void testA() {
            assertEquals("testA", name.getMethodName());
        }

        @Test public void testB() {
            assertEquals("testB", name.getMethodName());
        }
    }

Interceptors in JUnit 4.7

May 5th, 2009 by David Saff in Uncategorized

For both of you that read this blog, and haven’t already seen it, there’s some fun stuff brewing in JUnit 4.7.