Question

According this link: powermock

If I have this class

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();
        }
}

I can test it following:

@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);
        }
}

I have following question:

How Can I test this 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);
            }

    }

I use powerMock version 1.5

Was it helpful?

Solution

For Mockito/PowerMockito you can use the whenNew() function. It would probably look something like this once you expand it out a bit:

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

Also, when using Mockito try using Mockito.mock() to create the Mock objects (in this case fileMock.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top