java - 任何模拟 Files.write(...) 方法的方法?

标签 java unit-testing junit mockito powermockito

我需要有关单元测试用例的帮助。
我想模拟静态方法 write(Path path, byte[] bytes, OpenOption... options)java.nio.file.Files类(class)。

我试过例如。以这种方式:

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 .

我该怎么做才能正确?

最佳答案

我只有一个写入文件系统的服务,所以我决定只使用 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);

关于java - 任何模拟 Files.write(...) 方法的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36316601/

相关文章:

java - 如何从 Java 代码创建 gml 文件

java - 如何手动添加依赖到Android Studio

c++ - 使用升压测试和不应编译的测试的最佳实践

java - 当单元测试方法具有断言而不是异常时,最佳实践是什么?

java - 如果变量值为 null,则忽略 JUnit 测试

java - EclipseLink JPA 在关系属性中使用非实体作为目标实体

java - 包装 JAXBElement 实例的字符串

Java 有序映射

asp.net-mvc - ASP.Net MVC 中 HttpContext 和可测试 Controller 的最佳实践

php - 单元测试中的依赖关系