junit5 mock静态方法 Mockito.mockStatic()
junit5 mock静态方法
环境
jdk11 , junit5 ,springboot
pom
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <!-- mockito static method --> <dependency> <groupId>org.mockito</groupId> <artifactId>mockito-inline</artifactId> <version>4.1.0</version> <scope>test</scope> </dependency>
代码
@SpringBootTest class MockStaticTest { @InjectMocks TestService testService; @Test void apply2() { try (MockedStatic<TestUtil> mock = Mockito.mockStatic(TestUtil.class)) { mock.when(TestUtil::m).thenReturn("bar"); String t = testService.m("a"); System.out.println(t); Assertions.assertNotNull(t); } } @Service public static class TestService { public String m(String name) { String t = TestUtil.m(); System.out.println("m -> " + name); return t + " " + name; } } public static class TestUtil { public static String m() { System.out.println("a"); return "静态方法"; } } }