Sunday 25 August 2019

Static method MockUp effect is global

Use mockit.MockUp.MockUp() to mock public static methods. One caveat is that the mocked behaviour applies to other test methods as well. (test2() prints "abc", which is surprising, isn't it?)

@ExtendWith(value = {MockitoExtension.class})
@RunWith(JUnitPlatform.class)
class MyTest {
    
    @Test
    void test1() throws IOException {
        new MockUp<System>() {
            @mockit.Mock
            public String getProperty(String key){
                return "abc";
            }
            
        };
        
        assertThat(System.getProperty("a"), is("abc"));
    }
    
    @Test
    void test2() throws IOException {
        System.out.println(System.getProperty("a")); //Prints abc
    }
    

}

Junit 5 temp directory quick start

The tempDirectory extension makes it quite handy to test file reading/writing functions.

Maven dependency

<dependency>
   <groupId>org.junit-pioneer</groupId>
   <artifactId>junit-pioneer</artifactId>
   <version>0.1.2</version>
   <scope>test</scope>
</dependency>

Java

@Test
@ExtendWith(TempDirectory.class)
void withProperties(@TempDir Path tempDir) throws IOException {
    Path path = tempDir.resolve("env.properties");
    String properties = "a=b";
    Files.write(path, properties.getBytes());
    Map<String, Object> props = EnvPropertiesLoader.loadEnvProperties();
    assertThat(props.get("a"), is("b"));
}