2016-10-19 16 views
0

を返す静的メソッドをからかう:この静的メソッドのPowermockitoは私がpowermockitoを使用して模擬したいコードのこの部分を持っているMockito.mock

long size = FileUtility.getFileFromPath(uri.getPath()).length()) 

実装は簡単です:

public static File getFileFromPath(String filePath) { 
    return new File(filePath); 
} 

このコードをテストに書くと、テストは失敗します。この例外に

PowerMockito.mockStatic(FileUtility.class); 
File fileMock = mock(File.class); 
PowerMockito.when(FileUtility.getFileFromPath(anyString())).thenReturn(fileMock); 
Mockito.doReturn(12).when(fileMock.length()); 

私は(私が今行ったように私は、別々の変数に モック(File.class)を抽出しなければならない)の前に、エラーを見てきました
org.mockito.exceptions.misusing.UnfinishedStubbingException: 
Unfinished stubbing detected here: 
-> at nl.mijnverzekering.entities.declareren.NotaPdfMetadataTest.mockFileSize(NotaPdfMetadataTest.java:273) 

E.g. thenReturn() may be missing. 
Examples of correct stubbing: 
    when(mock.isOk()).thenReturn(true); 
    when(mock.isOk()).thenThrow(exception); 
    doThrow(exception).when(mock).someVoidMethod(); 
Hints: 
1. missing thenReturn() 
2. you are trying to stub a final method, you naughty developer! 
3: you are stubbing the behaviour of another mock inside before 'thenReturn' instruction if completed 

。 ここで何がうまくいかないのですか?戻り値としてモックオブジェクトを使用しているからですか?それを解決するには?

回避策ソリューション:私はFileUtilityに、このメソッドを追加したい場合は私のテストは成功するだろうもちろんの :単に、その後

public static long getFileSizeFromFilePath(String filePath) { 
    return getFileFromPath(filePath).length(); 
} 

PowerMockito.mockStatic(FileUtility.class); 
    PowerMockito.when(FileUtility.getFileSizeFromFilePath(anyString())).thenReturn(size); 

しかし、私は予防したいのですがそれらの不要なメソッドのリストをFileUtilityに追加します(例外の理由を理解してください)

答えて

0

ここで何が問題になりますか?私は模擬オブジェクトを 戻り値として使用しているからですか?それを解決するには?

この行は間違っている:

Mockito.doReturn(12).when(fileMock.length()); 

署名はモックが通過しなければならないので、T when(T mock)ではなく、メソッド呼び出し:

Mockito.doReturn(12L).when(fileMock).length(); 

は、これも動作します:

Mockito.when(fileMock.length()).thenReturn(12L); 
関連する問題