简体   繁体   中英

Why isn't my JUnit test for a file's existence working?

 @Test
    public void createFileTest() throws Exception {
        File file = new File("somefile.txt");
        boolean expectedResult = true;
        boolean actualResult = false;
        if (file.exists()){
            actualResult = true;
        }
        assertEquals(expectedResult, actualResult);
    }

I have a method that creates or rewrites a Json file. The test method I have now written cannot determine the file exists despite the file being visible in the directory.

How is file.exists() being implemented incorrectly, or what is a working alternative?

When testing this myself, the function seem's to be working as I would expect.

If somefile.txt does not exist then the test should fail, however if it does exist then the test passes.

Just to clear up on what the constructor and .exists() do:

File file = new File("somefile.txt");

This just creates a new File instance, an abstract pathname not an actual file.

file.exists()

Said best by the javadoc:

Tests whether the file or directory denoted by this abstract pathname exists.

If this test still fails, I would suggest adding

file.getAbsoluteFile()

this returns a String of the absolute path where this File would be if it existed.

Your question is not about UnitTesting, but about how to access file in Java.

The way you asccess the file:

File file = new File("somefile.txt");

the file must be in the same folder on the file system as your Java source file containig the test.


Just for the records:

UnitTests do not access the file system (or any other expensive resources).

In UnitTest you mock those resources (or the classes working with them) using a mocking framework like Mockito, JMock(-it) or alike.

Also you do not test 3rd party classes (like java.io.File ). You test your classes, how they communicate with this dependency:

@Test
public void writeTo_FileNotExisting_CreatesTheFile(){
   // arrange
   File targetFile = mock(File.class);
   when(targetFile.exists()).thenReturn(false);

   // act
   new YourJsonWriter().writeTo(targetFile);

   // assert
   verify(targetFile).createNewFile();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM