下記のインスタンスを生成する部分をMockにしたい。
1 | NovelSource novelSource = new NovelSource(url); |
そこで、PowerMockitoを使用してみる。
1 2 3 4 5 6 | < dependency > < groupId >org.powermock</ groupId > < artifactId >powermock-api-mockito</ artifactId > < version >1.6.6</ version > </ dependency > |
使用方法はこんな感じ。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | @RunWith (PowerMockRunner. class ) @PrepareForTest ({ NovelManagerImpl. class }) @PowerMockIgnore ( "javax.management.*" ) public class NovelManagerImplTest extends BaseManagerMockTestCase { @Mock private NovelSource novelSource; @Mock private Logger log; @Mock private NovelDao novelDao; @Mock private NovelInfoManager novelInfoManager; @Mock private NovelChapterManager novelChapterManager; @InjectMocks private NovelManagerImpl novelManager = new NovelManagerImpl(); @Test public void testAdd() throws Exception { String fileName = this .getClass().getClassLoader().getResource( "novel/20160924/test.html" ).getPath(); File file = new File(fileName); NovelSource novelSource = new NovelSource( new Source(file)); { // 初期化 MockitoAnnotations.initMocks( this ); // NovelSourceをnewするとき、thenReturn(~)のインスタンスを返却する PowerMockito.whenNew(NovelSource. class ).withArguments(url).thenReturn(novelSource); } } |
コンストラクタに引数を渡したいときは、withArguments()を使用する。
しかし、カバレッジが測定出来ないので注意。
初めまして。
是非とも使ってみたいライブラリです!