我有一个最后的课,类似这样:
public final class RainOnTrees{
public void startRain(){
// some code here
}
}
Run Code Online (Sandbox Code Playgroud)
我在其他类中使用此类,如下所示:
public class Seasons{
RainOnTrees rain = new RainOnTrees();
public void findSeasonAndRain(){
rain.startRain();
}
}
Run Code Online (Sandbox Code Playgroud)
在我的JUnit测试类中,Seasons.java我想模拟这个RainOnTrees类.我怎么能和Mockito一起做这件事?
我有一个非常简单的测试用例,它使用的是Mockito和Spring Test框架.当我做
when(pcUserService.read("1")).thenReturn(pcUser);
Run Code Online (Sandbox Code Playgroud)
我得到了这个例外.
org.mockito.exceptions.misusing.MissingMethodInvocationException:
when() requires an argument which has to be 'a method call on a mock'.
For example:
when(mock.getArticles()).thenReturn(articles);
Also, this error might show up because:
1. you stub either of: final/private/equals()/hashCode() methods.
Those methods *cannot* be stubbed/verified.
2. inside when() you don't call method on mock but on some other object.
at com.project.cleaner.controller.test.PcUserControllerTest.shouldGetPcUser(PcUserControllerTest.java:93)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44)
Run Code Online (Sandbox Code Playgroud)
我尝试过不同的方法,但继续收到此错误消息.我正在使用Spring 3.1.0.RELEASE和Mockito.请分享并指导我正确的方向.
我正在使用Mockito来模拟我正在编写测试的同一个类中的方法.我已经在SO上看到了其他答案(同一类中的模拟方法),但可能是我误解了它们,因为我遇到了问题.
class Temp() {
public boolean methodA(String param) {
try {
if(methodB(param))
return true;
return false;
} catch (Exception e) {
e.printStackTrace();
}
}
}
Run Code Online (Sandbox Code Playgroud)
我的测试方法:
@Test
public void testMethodA() {
Temp temp = new Temp();
Temp spyTemp = Mockito.spy(temp);
Mockito.doReturn(true).when(spyTemp).methodB(Mockito.any());
boolean status = temp.methodA("XYZ");
Assert.assertEquals(true, status);
}
Run Code Online (Sandbox Code Playgroud)
然而,由于方法B的定义被执行,我打印出了预期.我的理解是使用spyTemp来模拟methodB的定义.然而,情况似乎并非如此.
有人可以解释我哪里出错吗?
我正在从我正在进行的项目中删除Powermock,所以我试图仅用Mockito(mockito-core-2.2.28)重写一些现有的单一测试.
当我运行测试时,我有以下错误:
org.mockito.exceptions.base.MockitoException:
不能模拟/间谍类com.ExternalpackagePath.Externalclass
Mockito不能嘲笑/间谍,因为:
- 最后一堂课
我知道,这个问题已经被问(如何嘲弄与一的Mockito final类,调用final类与静态的Mockito方法Mock对象),但我没有找到我要找的答案.
这是我的代码的摘录:
public class MyClassToTest extends TestCase {
private MyClass myClass;
@Mock private Externalclass ext; // This class is final, I would like to mock it
@Override
protected void setUp() throws Exception {
MockitoAnnotations.initMocks(this); // <<<< The exception is thrown here
ext = Mockito.mock(Externalclass.class);
}
}
Run Code Online (Sandbox Code Playgroud)
由于文档的Mockito中提到(https://github.com/mockito/mockito/wiki/What%27s-new-in-Mockito-2,§Mock的unmockable),我增加了org.mockito.plugins.MockMaker文件.这是我项目的树:
我还尝试将"resources"目录放在"src"中,在一个名为"test"的子目录中,但结果仍然相同.
我认为用Mockito v2嘲笑决赛是可能的.有人知道这里缺少什么吗?
谢谢!
我没有嘲笑ResourceBundle.getString().
这是我的代码:
ResourceBundle schemaBundle = Mockito.mock(ResourceBundle.class);
Mockito.when(schemaBundle.getString("testKey_testPropertyName_ect")).thenReturn("testString1");
Run Code Online (Sandbox Code Playgroud)
这在第二行给出以下异常:
java.util.MissingResourceException: Can't find resource for bundle $java.util.ResourceBundle$$EnhancerByMockitoWithCGLIB$$9e259f03, key testKey_testPropertyName_ect
at java.util.ResourceBundle.getObject(ResourceBundle.java:374)
at java.util.ResourceBundle.getString(ResourceBundle.java:334)
at com.foo.bar.resource.PropertyResourceTest.testGet(PropertyResourceTest.java:104)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:28)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:76)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)
at org.junit.runners.ParentRunner.run(ParentRunner.java:236)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
Run Code Online (Sandbox Code Playgroud)
对我来说,这看起来好像schemaBundle根本没有被嘲笑.但是debuger清楚地表明,实例是由mockito包裹的.
我也尝试过
Mockito.doReturn("testString1").when(schemaBundle).getString("testKey_testPropertyName_ect");
Run Code Online (Sandbox Code Playgroud)
但是这会返回相同的异常.
知道什么是错的吗?
我正在尝试解决一个简单的问题,并陷入Java内存模型兔子洞.
什么是最简单和/或最有效(判断调用此处),但无竞争(根据JMM精确定义)编写包含非最终引用字段的Java类的方法,该字段初始化为非空值构造函数,后来从未改变过,这样任何其他线程的后续访问都不能看到非空值?
破碎的起始示例:
public class Holder {
private Object value;
public Holder(Object value) {
if (value == null)
throw NullPointerException();
this.value = value;
}
public Object getValue() { // this could return null!
return this.value;
}
}
Run Code Online (Sandbox Code Playgroud)
而根据这篇文章,标记该领域volatile甚至不起作用!
public class Holder {
private volatile Object value;
public Holder(Object value) {
if (value == null)
throw NullPointerException();
this.value = value;
}
public Object getValue() { // this STILL could return null!!
return this.value;
}
} …Run Code Online (Sandbox Code Playgroud) 我正在为一个有两个方法methodA,methodB的类编写JUnit Test案例.我想在我的测试用例中模拟从methodA调用methodB我在我正在测试的类上使用spy,但仍然执行了methodB.
这是班级
public class SomeClass
{
public Object methodA(Object object)
{
object=methodB(object);
return object;
}
public Object methodB(Object object)
{
//do somthing
return object;
}
}
Run Code Online (Sandbox Code Playgroud)
这是测试类
@RunWith( org.powermock.modules.junit4.legacy.PowerMockRunner.class )
@PrepareForTest(SomeClass.class)
public class SomeClassTest {
private SomeClass var = null;
@Before
public void setUp() {
var=new SomeClass();
}
@After
public void tearDown()
{
var= null;
}
@Test
public void testMethodA_1()
throws Exception {
Object object =new Object();
SomeClass spy_var=PowerMockito.spy(var);
PowerMockito.when(spy_var.methodB(object)).thenReturn(object);
Object result = var.methodA(object);
assertNotNull(result);
}
}
Run Code Online (Sandbox Code Playgroud)
虽然我已经模拟了它,但方法B仍然可以调用它.但是PLease建议我使用适当的方法来模拟同一类的methodA中的methodB调用.
我正在尝试使用Mockito创建一个从Mock对象返回的Mock对象.具体来说,我正在尝试模拟PlayerConnection我的程序可以用来检索IP地址的对象.
你可以PlayerConnection object 在这里找到更多相关信息.它返回一个InetSocketAddress然后InetAddress可以返回一个可以返回String与播放器的IP的a .但我无法走得那么远,因为我的第一次when(class.function()).thenReturn(returnVariable)投掷了NullPointerException.这是我的代码:
/**
* Creates a partial mock of a connection that can return an ip address.
*
* @param String
* The IP to return when the connection gets asked.
* @return
*/
private PlayerConnection newConnection(String ipString)
{
PlayerConnection playerConnection = mock(PlayerConnection.class);
InetSocketAddress inetSocketAddress = mock(InetSocketAddress.class);
InetAddress inetAddress = mock(InetAddress.class);
when(playerConnection.getAddress()).thenReturn(inetSocketAddress);
when(inetSocketAddress.getAddress()).thenReturn(inetAddress);
when(inetAddress.getHostAddress()).thenReturn(ipString);
return playerConnection;
}
Run Code Online (Sandbox Code Playgroud)
这是堆栈跟踪,发生在when(playerConnection.getAddress()).thenReturn(inetSocketAddress):
Tests run: 1, …Run Code Online (Sandbox Code Playgroud) 我正在尝试模拟一个SimpleDateFormat对象,但 Mockito 说我的参数数量错误。代码:
SimpleDateFormat spyDateFormat = spy(new SimpleDateFormat(DateFormatManager.MAIN_ACTIVITY_TITLE_FORMAT));
// exception points to below line
when(spyDateFormat.format(any(Date.class))).thenReturn("foo format");
Run Code Online (Sandbox Code Playgroud)
例外:
org.mockito.exceptions.misusing.InvalidUseOfMatchersException:
Invalid use of argument matchers!
3 matchers expected, 1 recorded:
Run Code Online (Sandbox Code Playgroud)
该方法存在于其父 DateFormat 中:
http://docs.oracle.com/javase/7/docs/api/java/text/DateFormat.html#format(java.util.Date)
尝试切换到 DateFormat,使用spy. 没有运气。