Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.1k views
in Technique[技术] by (71.8m points)

Best way to test Android class which writes a log file

I have a question about how best to test a logger class I am working on for Android. This logger class writes to an Android log file in internal storage during "real" usage, but I'm trying to figure out the best way to mock this for testing purposes since it seems there is no equivalent for getFilesDir() during instrumentation tests.

Ideally I would be able to write a log file from my logger class during my test, and then read that file during my test checking that my logs look like I expect.

I have looked around a bit and tried using a TemporaryFolder for this purpose in my test. I am able to read and write this file from my test class beautifully, but I am unable to write this file from my MyLogger class in the test instance. In my MyLogger class constructor where I am trying to create a file in the TemporaryFolder directory during my test, I get this error:

open failed: EROFS (Read-only file system)

Can you help me understand the best way for me to test my logger class? One of the reasons I would like to use actual files here is because I would like to have test coverage for file rotation as well, if possible.

Instrumentation Test

@RunWith(AndroidJUnit4.class)
public class MyLoggerTest{
    @Rule public TemporaryFolder mTempFolder = new TemporaryFolder();
    @Test
    public void testCreateLogFile() {
        try {
            mTempFolder.newFolder("baseFolder");
            MyLogger logger = new MyLogger(mTempFolder + "/baseFolder/");
        } catch(Exception e) {
            fail(e.getMessage());
        }
    }
}

Class Constructor

public MyLogger(String path) {
    File logFile = new File(path + "myLog.log");
    try {
        if (!logFile.createNewFile()) {
            Log.d("MyAppTag", "createNewFileFailed");
        }
    } catch (IOException e) {
        e.printStackTrace();
        Log.e("MyAppTag", e.getMessage());
    }
}

Thank you! I love you Stack Overflow community!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神解答

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...