有什么方法可以模拟Files.write(...)方法吗?

问题描述 投票:3回答:1

我需要单元测试用例的帮助。我想模拟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

我该怎么做对吗?

java unit-testing junit mockito powermockito
1个回答
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);
© www.soinside.com 2019 - 2024. All rights reserved.