Mock静态方法 MockedStatic Mockito.mockStatic

Mock 静态方法

Mockito 3.4.0 开始可 Mock 静态方法, 这里使用junit4

pom

<dependency>
		    <groupId>org.mockito</groupId>
		    <artifactId>mockito-inline</artifactId>
		    <version>3.7.7</version>
		    <scope>test</scope>
		</dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <scope>test</scope>
        </dependency>

代码

@RunWith(MockitoJUnitRunner.class)
class MockStaticTest {
    private Utils target  = new Utils();

    @Test
    void t() {
        LocalDate yearOf2000 = LocalDate.of(2000, 1, 1);
        try (MockedStatic theMock = Mockito.mockStatic(LocalDate.class)) {
            theMock.when(LocalDate::now).thenReturn(yearOf2000);

            System.out.println(target.getCurrentDate());
            Assertions.assertEquals(2000, target.getCurrentDate().getYear());
        }
    }


    public class Utils {
        public LocalDate getCurrentDate() {
            return LocalDate.now();
        }
    }

}

.

经验分享 程序员 微信小程序 职场和发展