JUnit 5测试公共方法时如何Mock私有方法?
用JUnit 5测试
School类并Mock私有方法 要测试School类的getFullNameWithSchool方法并Mock私有方法getSchoolName,可以用PowerMock配合JUnit 5实现(Mockito本身不支持直接Mock私有方法),具体步骤如下:
1. 添加必要依赖(Maven示例)
<dependencies> <!-- JUnit 5核心依赖 --> <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter-api</artifactId> <version>5.9.2</version> <scope>test</scope> </dependency> <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter-engine</artifactId> <version>5.9.2</version> <scope>test</scope> </dependency> <!-- PowerMock适配JUnit 5和Mockito的依赖 --> <dependency> <groupId>org.powermock</groupId> <artifactId>powermock-module-junit5</artifactId> <version>2.0.9</version> <scope>test</scope> </dependency> <dependency> <groupId>org.powermock</groupId> <artifactId>powermock-api-mockito2</artifactId> <version>2.0.9</version> <scope>test</scope> </dependency> </dependencies>
2. 编写测试类
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit5.PowerMockExtension; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.powermock.api.mockito.PowerMockito.*; @ExtendWith(PowerMockExtension.class) @PrepareForTest(School.class) // 告知PowerMock需要修改该类字节码以支持私有方法Mock class SchoolTest { @Test void getFullNameWithSchool_returnsExpectedValue() throws Exception { // 创建被测试类实例 School school = new School(); // Mock私有方法getSchoolName:当传入参数"HMS"时,返回指定模拟值 when(school, "getSchoolName", "HMS").thenReturn("Mocked HMS"); // 调用待测试的公共方法 String result = school.getFullNameWithSchool(); // 断言结果符合预期 assertEquals("SK Mocked HMS", result); } }
补充说明
@PrepareForTest(School.class)是必填项,PowerMock需要通过修改目标类的字节码,才能实现私有方法的Mock逻辑。- 通常不推荐Mock私有方法,更合理的做法是将私有方法的逻辑提取为独立的依赖类(比如
SchoolNameResolver),这样可以用普通Mockito直接Mock依赖,测试逻辑更清晰,也符合面向对象的设计原则。
内容的提问来源于stack exchange,提问作者SkClass
相关产品推荐
相关产品推荐

