2017-02-03 10 views
2

プライベートメソッドを持ち、その本体に別のプライベートメソッドを呼び出すクラスがあります。だから私は最初のプライベートメソッドを呼び出すと、2番目のプライベートメソッドを模擬したい。PowerMockitoは私的プライベートメソッドの代わりに実際のメソッドを呼び出しています

public class ClassWithPrivateMethod { 

    private int count; 

    public ClassWithPrivateMethod() { 
    } 

    private void countDown() { 
     while (isDecrementable()) 
      count--; 
    } 

    private boolean isDecrementable() { 

     throw new IllegalArgumentException(); 
//  if (count > 0) return true; 
//  return false; 
    } 
} 

とテストクラス:

@RunWith(PowerMockRunner.class) 
@PrepareForTest(ClassWithPrivateMethodTest.class) 
public class ClassWithPrivateMethodTest { 

    private int count; 
    private ClassWithPrivateMethod classWithPrivateMethod; 

    @Before 
    public void setUp() throws Exception { 
     count = 3; 
     classWithPrivateMethod = PowerMockito.spy(new ClassWithPrivateMethod()); 
    } 

    @Test 
    public void countDown() throws Exception { 

     Whitebox.setInternalState(classWithPrivateMethod, "count", count); 
     PowerMockito.doReturn(true, true, false).when(classWithPrivateMethod, "isDecrementable"); 

     Whitebox.invokeMethod(classWithPrivateMethod, "countDown"); 

     int count = Whitebox.getInternalState(classWithPrivateMethod, "count"); 

     assertEquals(1, count); 

     PowerMockito.verifyPrivate(classWithPrivateMethod, times(3)).invoke("isDecrementable"); 
    } 
} 

私はWhitebox.invokeMethod(classWithPrivateMethod, "countDown");と、このようなモック秒1、PowerMockito.doReturn(true, true, false).when(classWithPrivateMethod, "isDecrementable");することにより、第1のプライベートメソッドを呼び出しここでは一例です。あなたが参照したようにisDecrementableメソッドはtruetruefalseの値を返しますが、PowerMockitoは実際のメソッドを呼び出しています。

私はこれらの依存関係を使用しています:

<dependency> 
    <groupId>junit</groupId> 
    <artifactId>junit</artifactId> 
    <version>4.12</version> 
</dependency> 
<dependency> 
    <groupId>org.powermock</groupId> 
    <artifactId>powermock-api-mockito</artifactId> 
    <version>1.6.5</version> 
</dependency> 
<dependency> 
    <groupId>org.powermock</groupId> 
    <artifactId>powermock-module-junit4</artifactId> 
    <version>1.6.5</version> 
    <scope>test</scope> 
</dependency> 
<dependency> 
    <groupId>org.mockito</groupId> 
    <artifactId>mockito-core</artifactId> 
    <version>1.10.19</version> 
</dependency> 

私のテストで間違っていますか?

答えて

4

私は、この行に誤りが見つかりました:それがあるべき

@PrepareForTest(ClassWithPrivateMethodTest.class) 

を:

@PrepareForTest(ClassWithPrivateMethod.class) 
関連する問題