差分
このページの2つのバージョン間の差分を表示します。
| 両方とも前のリビジョン前のリビジョン次のリビジョン | 前のリビジョン | ||
| study:java:powermock:mocking [2020/05/12 01:06] – [Using an ArgumentCaptor of Collection type] banana | study:java:powermock:mocking [2020/05/12 01:19] (現在) – [Mock Protected Parent Method] banana | ||
|---|---|---|---|
| 行 148: | 行 148: | ||
| Parent classにあるprotected methodの振る舞いを定義する例を紹介する。 | Parent classにあるprotected methodの振る舞いを定義する例を紹介する。 | ||
| + | 親クラスの例を次に示す。 | ||
| <code java> | <code java> | ||
| package parent; | package parent; | ||
| 行 154: | 行 155: | ||
| protected void foo(String arg1, String arg2) { | protected void foo(String arg1, String arg2) { | ||
| - | //Logic here | + | //some logic here |
| } | } | ||
| } | } | ||
| </ | </ | ||
| + | |||
| + | 子クラスの例を次に示す。 | ||
| + | <code java> | ||
| + | package child; | ||
| + | |||
| + | import parent.Parent; | ||
| + | |||
| + | public class Child extends Parent { | ||
| + | |||
| + | public String bar() { | ||
| + | //call parent method | ||
| + | this.foo(); | ||
| + | |||
| + | //Child logic here | ||
| + | } | ||
| + | } | ||
| + | </ | ||
| + | |||
| + | テストクラスの例を次に示す。 | ||
| + | <code java> | ||
| + | package child; | ||
| + | |||
| + | import parent.Parent; | ||
| + | import static org.mockito.Matchers.anyObject; | ||
| + | import static org.powermock.api.mockito.PowerMockito.doNothing; | ||
| + | import static org.powermock.api.mockito.PowerMockito.spy; | ||
| + | import static org.powermock.api.mockito.PowerMockito.when; | ||
| + | import org.powermock.core.classloader.annotations.PrepareForTest; | ||
| + | |||
| + | @PrepareForTest({Parent.class, | ||
| + | public class ChildTest { | ||
| + | //Class Under Test | ||
| + | Child cut; | ||
| + | |||
| + | @Before | ||
| + | public void setUp() throws Exception { | ||
| + | //Partial mock to mock methods in parent class | ||
| + | cut = spy(new Child()); | ||
| + | |||
| + | //stub parent foo method | ||
| + | doNothing().when(cut, | ||
| + | } | ||
| + | |||
| + | @Test | ||
| + | public void testBar() { | ||
| + | //call test method | ||
| + | cut.bar(); | ||
| + | //assertion here | ||
| + | } | ||
| + | } | ||
| + | |||
| + | </ | ||
| + | ここでは、親クラスのfooメソッドが呼ばれた際、何もしない(doNothing)を実装している。 | ||