PowerMock类对方法获得的对象是否有期望的新方法模拟



根据此链接:powermock

如果我有这类

public class PersistenceManager {
        public boolean createDirectoryStructure(String directoryPath) {
                File directory = new File(directoryPath);
                if (directory.exists()) {
                        throw new IllegalArgumentException(""" + directoryPath + "" already exists.");
                }
                return directory.mkdirs();
        }
}

我可以测试如下:

@RunWith(PowerMockRunner.class)
@PrepareForTest( PersistenceManager.class )
public class PersistenceManagerTest {
        @Test
        public void testCreateDirectoryStructure_ok() throws Exception {
                final String path = "directoryPath";
                File fileMock = createMock(File.class);
                PersistenceManager tested = new PersistenceManager();
                expectNew(File.class, path).andReturn(fileMock);
                expect(fileMock.exists()).andReturn(false);
                expect(fileMock.mkdirs()).andReturn(true);
                replay(fileMock, File.class);
                assertTrue(tested.createDirectoryStructure(path));
                verify(fileMock, File.class);
        }
}

我有以下问题:

如何测试此类:

public class PersistenceManager {
            public boolean createDirectoryStructure(String directoryPath) {
                    File directory = getFile(directoryPath);
                    if (directory.exists()) {
                            throw new IllegalArgumentException(""" + directoryPath + "" already exists.");
                    }
                    return directory.mkdirs();
            }
            public File getFile(String directoryPath){
                return new File(directoryPath);
            }
    }

我使用powerMock 1.5版

对于Mockito/PowerMockito,可以使用whenNew()函数。一旦你稍微扩展一下,它可能会看起来像这样:

PowerMockito.whenNew(File.class).withArguments(directoryPath).thenReturn((File) fileMock)

此外,当使用Mockito时,请尝试使用Mockito.mock()创建Mock对象(在本例中为fileMock.

相关内容

  • 没有找到相关文章

最新更新