简体   繁体   English

如何在另一个类中模拟一个类 junit mockito

[英]How to mock a class in another class junit mockito

Following are the 2 classes defined as:以下是定义为的 2 个类:

Class1{
   public method1
    {
        class2.getInstance().method2();
    }
}

Class2{
   public static getInstance() { .... }

   public method2() { .... }

   public Class3 obj = new Class3();
}

I need to write junit test for method1 of class1.我需要为 class1 的 method1 编写 junit 测试。 But I need to know how can I mock getInstance() and method2() of class2.但是我需要知道如何模拟 class2 的 getInstance() 和 method2()。

Also, please tell me how can I mock object of Class3.另外,请告诉我如何模拟 Class3 的对象。

If you find it hard to write a good test for your class, you should redesign your class for better testability, that's the reason TDD is also called Test Driven Design .如果你发现很难为你的类编写一个好的测试,你应该重新设计你的类以获得更好的可测试性,这就是 TDD 也被称为测试驱动设计的原因。 It should never be difficult to write a test for a simple class.为一个简单的类编写测试应该从来都不难。

However,然而,

For this task (eg mocking new ) you need another framework.对于此任务(例如模拟new ),您需要另一个框架。 For example PowerMock .例如PowerMock

So man, guys which already answered you are right.所以伙计,已经回答你的人是对的。

If you find it hard to write a good test for your class, you should redesign your class for better testability, that's the reason TDD is also called Test Driven Design.如果你发现很难为你的类编写一个好的测试,你应该重新设计你的类以获得更好的可测试性,这就是 TDD 也被称为测试驱动设计的原因。 It should never be difficult to write a test for a simple class.为一个简单的类编写测试应该从来都不难。

However,然而,

how to mock static methods is described here PowerMockito mock single static method and return object (thanks to Jorge) how to partially mock a class is already described here: How to mock a call of an inner method from a Junit此处描述了如何模拟静态方法 PowerMockito 模拟单个静态方法并返回对象(感谢 Jorge) 如何部分模拟一个类已在此处描述:How to mock a call of an inner method from a Junit

I can add following:我可以添加以下内容:

If you really have good reasons to do what you want I advice you further:如果你真的有充分的理由去做你想做的事,我会进一步建议你:

You can use Whitebox.setInternalState() method of powermock library in order to mock object of Class3.您可以使用 powermock 库的Whitebox.setInternalState()方法来模拟 Class3 的对象。

Whitebox.setInternalState(class2, "obj", class3Mock);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM