JUnitを経由してあざけるファイルの読み取り/書き込み

lemoncodes:

どのようにJUnitを介して、あなたのモックファイルの読み取り/書き込みを行いますか?

ここに私のシナリオです

MyHandler.java

public abstract class MyHandler {

    private String path = //..path/to/file/here

    public synchronized void writeToFile(String infoText) {
        // Some processing
        // Writing to File Here
        File file = FileUtils.getFile(filepath);
        file.createNewFile();
        // file can't be written, throw FileWriteException
        if (file.canWrite()) {
            FileUtils.writeByteArrayToFile(file, infoText.getBytes(Charsets.UTF_8));
        } else {
            throw new FileWriteException();
        }
    }

    public String readFromFile() {
        // Reading from File here
        String infoText = "";
        File file = new File(path);
        // file can't be read, throw FileReadException
        if (file.canRead()) {
            infoText = FileUtils.readFileToString(file, Charsets.UTF_8);        
        } else {
            throw FileReadException();
        }

        return infoText
    }

}

MyHandlerTest.java

@RunWith(PowerMockRunner.class)
@PrepareForTest({
    MyHandler.class
})
public class MyHandlerTest {

    private static MyHandler handler = null;
    // Some Initialization for JUnit (i.e @Before, @BeforeClass, @After, etc)

    @Test(expected = FileWriteException.class)
    public void writeFileTest() throws Exception {

       handler.writeToFile("Test Write!");

    }

    @Test(expected = FileReadException.class)
    public void readFileTest() throws Exception {

       handler.readFromFile();

    }
}

私はここでシナリオを実行しようとする場合、ソース上で与えられた、シナリオファイルが書き込み可能ではありません(書き込み許可許可されていない)、しかし、OKですfile(許可されていない読み取り許可)読めないです。それは、常にファイルを読み、私はすでに以下を経由してテストコード上のファイルパーミッションを変更しようとしています

File f = new File("..path/to/file/here");
f.setReadable(false);

しかし、私は、いくつかの読書をしたsetReadable()Windowsマシン上で実行したときに常にfalse(失敗)を返します。

プログラムでのJUnitに関連して、対象ファイルのファイルパーミッションを変更する方法はありますか?

注意

試験の対象ソースコードの意味は、変更することができないMyhandler.class修飾されるべきではない従来のコードです。

トーベン:

代わりに、オペレーティング・システム・ファイルのパーミッションにFileUtils.getFileを(...)モックと、それはcanWrite()/ canRead()のための具体的な値を返し、ファイル(例えば、匿名サブクラス)のインスタンスを返すようにする使用PowerMockを頼ります。

Mockitoと静的メソッドをモック

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=211798&siteId=1