【问题标题】:Any way to mock Files.write(...) method?有什么方法可以模拟 Files.write(...) 方法?
【发布时间】:2016-07-18 21:57:53
【问题描述】:

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

我试过了。这样:

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

我怎样才能做到正确?

【问题讨论】:

  • 为什么不按照你应该的方式使用假的FileSystem?模拟静态方法已经是一种主要的气味。
  • 第二路易斯--Java 的内置文件系统工具不适合模拟,即使使用 PowerMockito 之类的工具来超越 Mockito 的限制。
  • 谢谢路易斯。我使用了您建议的方式,并使用了this 库来创建内存文件系统。它对我来说是更好的解决方案。

标签: java unit-testing junit mockito powermockito


【解决方案1】:

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

【讨论】:

  • 这已经过时了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-18
  • 1970-01-01
  • 2015-11-03
  • 2015-12-07
  • 2011-01-03
相关资源
最近更新 更多