Exceptionを偽装する
JMockitのシンプルで強力なExpectations機能でテストコードが呼び出すモジュール側でのException発生も簡単に偽装できる
public class Sample1 { public String sample1( String in ) { try { return "[" + Other.calc( in ) + "]"; } catch ( Exception ex ) { return ""; } } }
Otherが次のようになっていて
public class Other { static public String calc( String in ) throws Exception { return in+in; } }
2回目の呼び出しの時にExceptionを発生させる場合次のようにそのまま書けばいい
package tutorial; import org.junit.After; import org.junit.Assert; import org.junit.Test; import mockit.*; public class SampleTest { @Test public void testSample1() { new Expectations(true) { Other mock; { mock.calc("a"); returns("aa"); mock.calc(""); throwsException( new Exception() ); } }; Sample1 s = new Sample1(); String ans1 = s.Test("a"); Assert.assertEquals("[aa]",ans1); String ans2 = s.Test(""); Assert.assertEquals("",ans2); } @After public void tearDown() { Mockit.tearDownMocks(); } }
このように Expectationsブロック中で throwsException を使うことにより任意のExceptionを簡単に発生させることが出来る。