9

単体テストでファイルを作成するロジックをカバーしたいと思います。File クラスをモックして、実際のファイルの作成を回避することは可能ですか?

4

3 に答える 3

8

このコード例のように、コンストラクターをモックします。「new File(...)」を呼び出すクラスを@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);
    }

}
于 2013-04-20T09:12:39.010 に答える
7

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

}
于 2015-08-26T00:16:07.347 に答える
6

それが可能かどうかはわかりませんが、そのような要件があり、FileServiceインターフェイスを作成することで解決しました。したがって、ファイルを直接作成/アクセスする代わりに、抽象化を追加します。その後、テストでこのインターフェイスを簡単にモックできます。

例えば:

public interface FileService {

    InputStream openFile(String path);
    OutputStream createFile(String path);

}

次に、これを使用してクラスで:

public class MyClass {

    private FileService fileService;

    public MyClass(FileService fileService) {
        this.fileService = fileService;
    }

    public void doSomething() {
        // Instead of creating file, use file service
        OutputStream out = fileService.createFile(myFileName);
    }
}

そしてあなたのテストで

@Test
public void testOperationThatCreatesFile() {
    MyClass myClass = new MyClass(mockFileService);
    // Do your tests
}

このようにして、モック ライブラリを使用せずにモックすることもできます。

于 2013-04-16T11:04:12.660 に答える