我需要单元测试用例的帮助。
我想模拟write(Path path, byte[] bytes, OpenOption... options)
类的静态方法java.nio.file.Files
。
我试过例如。就这样:
PowerMockito.doReturn(path).when(Files.class, "write", path, someString.getBytes());
在这种情况下,找不到该方法。
PowerMockito.doReturn(path).when(Files.class, PowerMockito.method(Files.class, "write", Path.class, byte[]
.class, OpenOption.class));
这次我有UnfinishedStubbingException
。
我该怎么做呢?
答案 0 :(得分:0)
我只有一个写入文件系统的服务,所以我决定只使用Mockito:
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.anyVararg;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import org.springframework.test.util.ReflectionTestUtils;
Path mockPath = mock(Path.class);
FileSystem mockFileSystem = mock(FileSystem.class);
FileSystemProvider mockFileSystemProvider = mock(FileSystemProvider.class);
OutputStream mockOutputStream = mock(OutputStream.class);
when(mockPath.getFileSystem()).thenReturn(mockFileSystem);
when(mockFileSystem.provider()).thenReturn(mockFileSystemProvider);
when(mockFileSystemProvider.newOutputStream(any(Path.class), anyVararg())).thenReturn(mockOutputStream);
when(mockFileSystem.getPath(anyString(), anyVararg())).thenReturn(mockPath);
// using Spring helper, but could use Java reflection
ReflectionTestUtils.setField(serviceToTest, "fileSystem", mockFileSystem);
只需确保您的服务执行以下调用:
Path path = fileSystem.getPath("a", "b", "c");
Files.write(path, bytes);