Junit测试中如何实例化继承jar包父类的派生类对象
解决方案
核心问题是你测试类中的Info对象未初始化,且jar包内自定义的Info类无法直接实例化,采用Mockito模拟对象框架可以完美解决这个问题,无需依赖jar包内部的实现逻辑,符合TDD的测试需求。
步骤1:引入Mockito依赖
如果你使用Maven管理项目,在pom.xml中添加以下依赖:
<dependency> <groupId>org.mockito</groupId> <artifactId>mockito-core</artifactId> <version>4.11.0</version> <scope>test</scope> </dependency> <dependency> <groupId>org.mockito</groupId> <artifactId>mockito-junit-jupiter</artifactId> <version>4.11.0</version> <scope>test</scope> </dependency>
如果是手动导入jar包到Eclipse,下载对应版本的Mockito核心包、byte-buddy、byte-buddy-agent、objenesis四个jar包导入即可。
步骤2:修正测试类代码
你原测试类存在三个问题:
- 成员变量初始化时传入的
info是null值 - 测试方法中调用实例的大小写不匹配
- 没有对
Info的依赖方法打桩,导致父类初始化或业务方法调用时缺值
修正后的测试类代码如下:
package jimmy.kilmer.com; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.Mockito.when; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import jarPackageImports.Info; @ExtendWith(MockitoExtension.class) class GameKITest { @Mock private Info info; private GameAI gameAiInstance; @BeforeAll static void setUpBeforeClass() throws Exception { } @AfterAll static void tearDownAfterClass() throws Exception { } @BeforeEach void setUp() throws Exception { // 对测试用到的Info方法打桩,根据你的测试需求设置返回值 // 假设screenWidth和screenHeight是父类从info的对应方法获取,此处按你的期望数组尺寸设置 when(info.getScreenWidth()).thenReturn(1600); // 1600/20=80 匹配你的预期数组宽度 when(info.getScreenHeight()).thenReturn(1300); // 1300/20=65 匹配你的预期数组高度 // 如果测试update方法,补充对应方法的打桩 // when(info.getVelocity()).thenReturn(你需要的速度值); // when(info.getX()).thenReturn(10); // when(info.getY()).thenReturn(20); // 实例化测试对象 gameAiInstance = new GameAI(info); } @AfterEach void tearDown() throws Exception { } @Test void testPopulateAllPossibleNodes() { // 1. given/arrange int[][] array1 = new int[80][65]; // 2. when/act int[][] array2 = gameAiInstance.populateAllPossibleNodes(); // 3. then/assert assertArrayEquals(array1, array2); } }
步骤3:补充缺失的打桩逻辑
如果运行测试仍然抛出异常,查看异常提示中调用的Info类的方法,按上述打桩格式补充对应的返回值即可,无需了解Info类的具体实现逻辑,所有依赖返回值都可以通过Mock自定义。
内容的提问来源于stack exchange,提问作者drexl spivey
相关产品推荐
相关产品推荐

