简体   繁体   中英

Using @Mock in Java for Unit Tests

Hello I am new to unit testing and want to test a method within a class that will generate a document to an external folder via an API. However, as this is just a test I don't want the document to actually show up in the external folder every time I test. I simply want to see if the document was created the right way. If I use @Mock and bring in the class that way will this prevent the document from showing up in the folder or is there another way to go about it. I am using Java and Mockito.

Make the solution testable. Usually, this can be done by making the code parameterized or using dependency injection.

By making the code parameterized, I mean that we pass the location or the folder where the document should be created. If you use Junit 5.4 or later, you can add @TempDir annotation to create a temporary folder for your tests. You can pass this temporary folder to your code. (Also, if you want to use an exact file location, you can modify it. eg: Path documentFile = location.resolve("document.txt"); ):

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import java.nio.file.Path;

class DocumentGeneratorTest {

    @TempDir
    private Path location;

    @Test
    void generatedDocumentShouldBeCorrect() {
        DocumentGenerator generator = new DocumentGenerator();

        generator.createDocument(location);

        // your assertion(s) on location
    }
}

If for some reason you can't or don't want to provide the location as a parameter, you can also use dependency injection. By abstracting away the IO related operations from the document generator to an interface, you can use a mock implementation during the test (your own mock or a library eg Mockito ). Once the mock is in use, you can assert on the document passed as a parameter to the mock to save.

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