PowerMock类是否有expectNew方法模拟方法获得的对象?

时间:2014-04-18 13:28:48

标签: java unit-testing mocking mockito 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版

1 个答案:

答案 0 :(得分:0)

对于Mockito / PowerMockito,您可以使用whenNew()功能。一旦你将它展开一点,它可能看起来像这样:

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

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