【问题标题】:Does PowerMock class has expectNew method analog for method obtained object?PowerMock 类是否具有用于方法获取对象的 expectNew 方法模拟?
【发布时间】:2014-04-18 13:28:48
【问题描述】:

根据此链接: 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 版

【问题讨论】:

    标签: java unit-testing mocking mockito powermock


    【解决方案1】:

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-10-19
      • 1970-01-01
      • 1970-01-01
      • 2020-05-26
      • 2015-11-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多