I want to cover a logic, that creates files with unit tests. Is it possible to mock File class and to avoid actual file creation?
To use PowerMock with Mockito, we need to apply the following two annotations in the test: @RunWith(PowerMockRunner. class): It is the same as we have used in our previous examples. The only difference is that in the previous example we have used MockitoUnitRunner.
PowerMock enables us to write good unit tests for even the most untestable code. For example, most of the mocking frameworks in Java cannot mock static methods or final classes. But using PowerMock, we can mock almost any class. PowerMock currently extends the EasyMock and Mockito mocking frameworks.
While Mockito can help with test case writing, there are certain things it cannot do viz:. mocking or testing private, final or static methods. That is where, PowerMockito comes to the rescue. PowerMockito is capable of testing private, final or static methods as it makes use of Java Reflection API.
Mock the constructor, like in this example code. Don't forget to put the class that will invoke the "new File(...)" in the @PrepareForTest
package hello.easymock.constructor;
import java.io.File;
import org.easymock.EasyMock;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.easymock.PowerMock;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
@RunWith(PowerMockRunner.class)
@PrepareForTest({File.class})
public class ConstructorExampleTest {
@Test
public void testMockFile() throws Exception {
// first, create a mock for File
final File fileMock = EasyMock.createMock(File.class);
EasyMock.expect(fileMock.getAbsolutePath()).andReturn("/my/fake/file/path");
EasyMock.replay(fileMock);
// then return the mocked object if the constructor is invoked
Class<?>[] parameterTypes = new Class[] { String.class };
PowerMock.expectNew(File.class, parameterTypes , EasyMock.isA(String.class)).andReturn(fileMock);
PowerMock.replay(File.class);
// try constructing a real File and check if the mock kicked in
final String mockedFilePath = new File("/real/path/for/file").getAbsolutePath();
Assert.assertEquals("/my/fake/file/path", mockedFilePath);
}
}
try PowerMockito
import org.mockito.Mockito;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
@PrepareForTest(YourUtilityClassWhereFileIsCreated.class)
public class TestClass {
@Test
public void myTestMethod() {
File myFile = PowerMockito.mock(File.class);
PowerMockito.whenNew(File.class).withAnyArguments().thenReturn(myFile);
Mockito.when(myFile.createNewFile()).thenReturn(true);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With