如何模拟未作为参数传递的对象 [英] How to mock Objects that are not passed as arguments

查看:89
本文介绍了如何模拟未作为参数传递的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

想象一下下面的课程

public class ClassToBeTested{

  private AnotherClass otherClass;

  public void methodToBeTested(){
     otherClass = new AnotherClass();
     String temp = otherClass.someMethod()

    // ...some other code that depends on temp

  }

}

现在,如果methodToBeTested被设计为接受AnotherClass的实例,那么我可以轻松地创建AnotherClass的模拟并告诉Mockito在调用someMethod()时返回一个值.但是,由于上述代码是根据AFAIK设计的,因此无法模拟AnotherClass,而测试此方法将取决于someMethod()返回的内容.

Now, if methodToBeTested was designed to accept an instance of AnotherClass I could easily create a mock of AnotherClass and tell Mockito to return a value i prefeer when someMethod() is called. However as the above code is designed AFAIK it's not possible to mock AnotherClass and testing this method will depend on what someMethod() returns.

无论如何,我可以使用Mockito或任何其他框架测试上述代码而不必依赖someMethod()返回的内容吗?

Is there anyway I can test the above code without beeing dependent on what someMethod() returns using Mockito or any other framework?

推荐答案

如果可用,可以使用Spring ReflectionTestUtils setField方法:

If available you can use the Spring ReflectionTestUtils setField method:

如果不使用反射功能直接编写自己的内容,请在此处提供一些信息:

If not write your own its pretty straight forward using reflection, some info here:

http://www.java2s.com/Code/Java/Reflection/Setprivatefieldvalue.htm

类似于以下内容,您将需要其他错误处理才能使其正常工作:

Something like the below, you will need additional error handling to get this to work properly:

public void setField(Object obj, String fieldName, Object value) {
    Field f = obj.getDeclaredField(fieldName);
    f.setAccessible(true);
    f.set(obj, value);
}

然后可以这样称呼它:

setField(objUnderTest, "fieldToSet", mockObject); 


编辑

我刚刚注意到您正在方法内部实例化它.如果绝对必要,则应遵循cyroxx发布的可能重复链接. 尽管这种做法通常是不良设计的标志,所以如果可以解决的话,我会的.


edit

I have just noticed that you are instantiating it inside the method. If that is absolutely necessary then you should follow the possible duplicate link posted by cyroxx. Although that practice is often a sign of bad design so if you can take it out I would.

这篇关于如何模拟未作为参数传递的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆