UTとPowerMock
4044 ワード
PowerMockの概要
テストする方法は、外部依存オブジェクト(接続getConnection、getAdminを取得)を多く参照し、外部オブジェクトは制御できず、シミュレーション(mock)外部オブジェクトは制御可能になります.
核心思想.
あなたがmockを必要とする方法はあなたのmockの対象調でなければなりません.元のオブジェクトは元の論理しか歩けない.
注釈が必要な場合:
@RunWith(PowerMockRunner.class)
@PrepareForTest ( { YourClassWithEgStaticMethod.class })
PowerMockito.mockStatic(ClassDependency.class);
PowerMockito.when(ClassDependency.isExist()).thenReturn(true);
PowerMockito.when(other.pub(Mockito.anyString())).thenCallRealMethod();
PowerMockito.when(other, "pri", Mockito.anyString()).thenReturn(" $$ I am handsome %% private.");
その他
PowerMockito.doNothing().when(mockUnder.dovoid(Mockito.anyString())); //WRONG
PowerMockito.doNothing().when(mockUnder).dovoid(Mockito.anyString()); //RIGHT
PowerMockito.doNothing().when(mockUnder,"dovoid","aa","bb"); //RIGHT
PowerMockito.when(mockUnder,"dovoid","aa","bb").thenAnswer(answer); //RIGHT
以下の書き方をお勧めします.
PowerMockito.doNothing().when(mockUnder,"dovoid","aa","bb");
PowerMockito.doNothing().when(UnderTest.class,"dovoid","aa","bb");
PowerMockito.when(mockUnder,"dovoid","aa","bb").thenAnswer(answer);
PowerMockito.when(under1, "isDpa", Mockito.anyString()).thenReturn(true);
Object[] args = invocation.getArguments();
入力パラメータに注意し、境界PowerMockito.when(under1.isDpa(Mockito.anyString())).thenReturn(true).thenReturn(false);
PowerMockito.doThrow(new NullPointerException()).when(other).doExcep(Mockito.anyString());
投げの異常はmockの方法で投げられるものでなければならない.そうしないとmockは異常を投げてしまうので、試験例の大きなcatchにAssertと書かないでください.assertTrue(true);プログラム投げ異常を判断するには、この異常はmockの時に投げた可能性が高いからです. @Test
public void test()
{
try
{
// do some test
}
catch (Exception e)
{
e.printStackTrace();
Assert.assertTrue(false);
}
}
UnderTest under = new UnderTest();
StudentMgr stuMgr = PowerMockito.mock(StudentMgr.class);
Class clazz = AbstractClass.class;
Field field = clazz.getDeclaredField("studentMgr");
field.setAccessible(true);
field.set(under, stuMgr);
よくある質問
spy() is used when you want the real code of the class you are spying on to do its job, but be able to intercept method calls and return values. mock() is used to make a new class that has the same interface as the class you are mocking, but with NO code inside...
注意事項
@BeforeClass // class
public static void setUpBeforeClass() throws Exception
{
}
@AfterClass // class
public static void tearDownAfterClass() throws Exception
{
}
@Before // Test
public void setUp() throws Exception
{
}
@After // Test
public void tearDown() throws Exception
{
}
mock singleton static final : mock before other code new it. mock単例は他のコードnewの前に