Powermock构造函数模拟对实例化对象没有影响

编程入门 行业动态 更新时间:2024-10-26 01:25:41
本文介绍了Powermock构造函数模拟对实例化对象没有影响的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 Class A{ B objB = new B(); objB.someBMethod(); } Class B{ public void someBMethof(){ C objC = new C(); } } class C{ int a=1; public C(){} public C(int v){ a=v; } } @RunWith( PoswerMockRunner.class ) @PrepareForTest({ A.class, B.class, C.class}) Class TestApp{ @Mock C mockC; PowerMockito.whenNew( C.class ).withNoArguments().thenReturn(mockC); }

上面的代码捕获了我正在尝试做的事情.但是whenNew()似乎不起作用,当我尝试调试时,创建的C对象不是模拟对象.不知道发生了什么.一些指针将不胜感激.谢谢

The above code captures what im trying to do. But the whenNew() does not seem to be working and when i try debuggin the C object created is not the mock. Dont know whats happening. Some pointers would be much appreciated. thanks

推荐答案

您提供了一些代码,非常感谢.但是下一次,请考虑发布一个sscce(正确的( Compilable )示例).

You provides some code, so thanks. But the next time, consider to post an sscce (Correct (Compilable) example).

我尝试过(并修复了您的代码),并且可以正常工作.这是我的代码版本:

I tried (and fix your code) and it works. This is my version of your code :

public class A { public int someAMethod() { B objB = new B(); return objB.someBMethod(); } } public class B { public int someBMethod() { C objC = new C(); return objC.getA(); } }

import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.when; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; @RunWith(PowerMockRunner.class) @PrepareForTest({ A.class, B.class, C.class }) public class TestApp { @Mock C mockC; @Test public void shoudlReturnTheCValue() throws Exception { when(mockC.getA()).thenReturn(666); PowerMockito.whenNew(C.class).withNoArguments().thenReturn(mockC); assertEquals(666, new A().someAMethod()); } }

我已经配置了一个具有以下依赖项的maven项目:

I have configured a maven project with the following dependencies :

<dependency> <groupId>org.powermock</groupId> <artifactId>powermock-api-mockito</artifactId> <version>1.5</version> <scope>test</scope> </dependency> <dependency> <groupId>org.powermock</groupId> <artifactId>powermock-module-junit4</artifactId> <version>1.5</version> <scope>test</scope> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <scope>test</scope> </dependency> <dependency> <groupId>org.mockito</groupId> <artifactId>mockito-all</artifactId> <version>1.9.5</version> <scope>test</scope> </dependency>

更多推荐

Powermock构造函数模拟对实例化对象没有影响

本文发布于:2023-10-31 06:39:46,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1545316.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   实例   对象   Powermock

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!