以下代码适用于PowerMockito版本1.7.3和MockitoVersion2.9.0
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和MockitoVersion2.12.0)时,我得到以下错误
org.mockito.exceptions.base.MockitoException:
Cannot mock/spy class java.nio.file.Paths
Mockito cannot mock/spy because :
- final class有什么想法可以导致这个问题,或者我需要改变什么?
谢谢你达米安
发布于 2017-11-11 17:02:47
我认为您将不得不降级/推迟升级到PowerMock v2.x。
见PowerMockito不兼容Mockito2,因为他们的版本是2.0.55-beta版。
这两个问题涵盖了所有PowerMock v2.x /moockitov2.x集成工作:
看起来目标是在PowerMock v2.0.0 (和一些Mockito2.x版本)中工作,但没有明确说明何时可用。
https://stackoverflow.com/questions/47240116
复制相似问题