public class FooTest { @Rule public final ExpectedException exception = ExpectedException.none(); @Test public void doStuffThrowsIndexOutOfBoundsException() { Foo foo = new Foo(); exception.expect(IndexOutOfBoundsException.class); foo.doStuff(); } }
Foo foo = new Foo() ; System.out.println( foo.doStuff() ) ; // "Do stuff with things." System.out.println( foo.doStuff( "stuff" ) ) ; // "Do stuff with things." System.out.println( foo.doStuff( "more stuff" ) ) ; // "Do more stuff with things." System.out.println( foo.doStuff( "stuff", "things" ) ) ; // "Do stuff with things." System.out.println( foo.doStuff( "things", "stuff" ) ) ; // "Do things with stuff."
@Test public void testFailuresOfClass() { Foo foo = new Foo(); try { foo.doStuff(); fail("doStuff() should not have succeeded"); } catch (IndexOutOfBoundsException expected) { // This is what we want. } try { foo.doStuff(null); fail("doStuff(null) should not have succeeded"); } catch (NullPointerException expected) { // This is what we want. } // etc for other failure modes }
private Foo foo; @Before public void setUp() { foo = new Foo(); } @Test(expected = IndexOutOfBoundsException.class) public void noArgsShouldFail() { foo.doStuff(); } @Test(expected = NullPointerException.class) public void nullArgShouldFail() { foo.doStuff(null); } @Test(expected = MyOwnException.class) public void nullAndEmptyStringShouldFail() { foo.doStuff(null,""); } @Test(expected = DomainException.class) public void doOtherStuffShouldFail() { foo.doOtherStuff(); }
Foo foo = new Foo(); ILogger logger = new LoggerToDb(); foo.setLoggerImpl(logger); foo.doStuff();
Foo foo = new Foo(); ILogger logger = new Logger(); foo.setLoggerImpl(logger); foo.doStuff();
@RunWith(JUnit4.class) public class FooTest { @Rule public ExpectedException exception = ExpectedException.none(); @Test public void doStuffThrowsIndexOutOfBoundsException() { Foo foo = new Foo(); exception.expect(IndexOutOfBoundsException.class); exception.expectMessage("happened?"); exception.expectMessage(startsWith("What")); foo.doStuff(); } }