Simon Kiely
Simon Kiely

Reputation: 6040

How can I write valid JUnit tests when mocking a filepath?

I am trying to write some JUnit tests for a set of methods which use some REST services on the web.

In general, within my methods, I am providing a filepath and a configuration as a parameter, but I expect things will get more complicated as I progress.

For right now, what are the best ways for me to write JUnit tests for the likes of :

public Answers changeFileToAnswer(String filePath, String mediaType) {
    File document = new File(filePath);
    Answers answers = restService.changeFileToAnswer(document, mediaType);
    return answers;
}

What kind of Unit tests can I write for a simple class like this? Testing the answers object would be an integration tests, since an external call is made here, right? What is good practise here? Is there a way to mock the filepath being passed in as a parameter?

Notes - This method is from a REST interface which will later be exposed through a GUI. I am currently testing it with POST calls from POSTman. Due to this, I am passing in a string for the filePath rather than a file object (as I could not post this to my server).

Thanks.

Upvotes: 1

Views: 9018

Answers (1)

Sergii Bishyr
Sergii Bishyr

Reputation: 8641

The test is not necessary to be integration. Your restService need to be mock or fake, so there is no real external call. For mocking filePath you can use JUnit TemporaryFolder.

public class TestClass{
    @Rule
    private TemporaryFolder folder = new TemporaryFolder();

    @Test
    public void testMethod(){
        File tempFile = folder.newFile("myfile.txt");
        classUnderTest.changeFileToAnswer(file.getPath(), mediaType);
    }
}

This rule will create a real file in file system which will be removed when tests finish execution.

UPD: You might also want to take a look at jimfs

Upvotes: 2

Related Questions