如何将PowerMockito的whenNew测试代码转为TestNG?求示例及学习资源
PowerMockito whenNew 逻辑转 TestNG 测试用例示例
转换后的TestNG测试用例
PowerMock与TestNG集成时,需在测试类上添加@PrepareForTest注解(指定包含new MsgTransmit()逻辑的类,比如Msg.class),同时确保引入PowerMock TestNG相关依赖。以下是修正并转换后的代码:
import org.testng.annotations.Test; import static org.powermock.api.mockito.PowerMockito.*; // 指定实际会new MsgTransmit的类,让PowerMock能拦截构造方法 @PrepareForTest(Msg.class) public class MsgTest { @Test public void testGetDetails() { // 修正原代码mock方法名错误,创建MsgTransmit的mock对象 MsgTransmit msgTransmitMock = mock(MsgTransmit.class); String userId = "id101"; String msg = "test_msg"; String output = "expected_output"; // 模拟指定参数的MsgTransmit构造方法 whenNew(MsgTransmit.class) .withArguments("transmit.get_msg", jdbcTemplate) .thenReturn(msgTransmitMock); // 模拟MsgTransmit的res方法返回预期结果 when(msgTransmitMock.res(msg, userId)).thenReturn(output); // 执行待测试方法 Msg.getDetails(userId, msg); } @Test public void testNullTransmitScenario() { // 模拟MsgTransmit任意构造参数都返回null whenNew(MsgTransmit.class) .withAnyArguments() .thenReturn(null); // 执行对应测试逻辑 // ... } }
TestNG学习资源推荐
- TestNG官方文档:权威官方指南,覆盖核心特性、注解、测试套件配置等全方面内容
- 菜鸟教程TestNG章节:适合入门的中文教程,讲解清晰,附带实用示例代码
- Stack Overflow TestNG标签区:可搜索具体问题,查看社区的解决方案与最佳实践
内容的提问来源于stack exchange,提问作者Keerthi Senthil
相关产品推荐
相关产品推荐

