2017-11-11 140 views
1

下面的代碼工作與PowerMockito 1.7.3版和版本的Mockito 2.9.0和的Mockito錯誤PowerMockito

import static org.junit.Assert.assertNotNull; 
import static org.junit.Assert.assertTrue; 

import java.nio.file.Files; 
import java.nio.file.Path; 
import java.nio.file.Paths; 

import org.junit.Test; 
import org.junit.runner.RunWith; 
import org.mockito.Mockito; 
import org.powermock.api.mockito.PowerMockito; 
import org.powermock.core.classloader.annotations.PrepareForTest; 
import org.powermock.modules.junit4.PowerMockRunner; 

@RunWith(PowerMockRunner.class) 
@PrepareForTest({FileUtils.class, Paths.class, Files.class}) 
public class FileUtilsTest { 

    @Test 
    public void testGetFileContents_Success() throws Exception { 
     String filePath = "c:\\temp\\file.txt"; 

     Path mockPath = PowerMockito.mock(Path.class); 
     PowerMockito.mockStatic(Paths.class); 
     PowerMockito.mockStatic(Files.class); 

     Mockito.when(Paths.get(Mockito.anyString())).thenReturn(mockPath); 
     Mockito.when(Files.readAllBytes(Mockito.isA(Path.class))).thenReturn("hello".getBytes()); 

     String fileContents = FileUtils.getFileContents(filePath); 
     assertNotNull(fileContents); 
     assertTrue(fileContents.length() > 0); 

     PowerMockito.verifyStatic(Paths.class); 
     Paths.get(Mockito.anyString()); 
     PowerMockito.verifyStatic(Files.class); 
     Files.readAllBytes(Mockito.isA(Path.class)); 
    } 

} 

但是 - 當我去下面的版本 - PowerMockito版本2.0.0 beta.5和版本的Mockito 2.12.0 - 我收到以下錯誤

org.mockito.exceptions.base.MockitoException: 
Cannot mock/spy class java.nio.file.Paths 
Mockito cannot mock/spy because : 
- final class 

任何想法可能會造成這個問題或者我需要改變什麼?

謝謝 達米安

回答

1

我認爲你必須要降級/推遲升級到PowerMock v2.x.

請參閱PowerMockito not compatible Mockito2 since their v2.0.55-beta release

所有PowerMock版本2.x/V2.X的Mockito整合工作是由這兩個問題涉及:

看起來像目標是讓它在PowerMock v2.0.0(和一些Mockito 2.x版本)中運行,但沒有明確說明何時可用。

+0

完美 - 謝謝@glytghing – Damien

相關問題