简体   繁体   English

与测试的类别不同的​​模拟方法

[英]Mocking methods from different class than tested one

I have an issue with writing a unit test for one of my methods. 我为其中一种方法编写单元测试时遇到问题。 It calls a method from a different class and to make it worse it makes some processing depending on a server connection so I would need to mock it somehow however I couldn't find an answer how to do that. 它从不同的类中调用方法,更糟糕的是,它会根据服务器连接进行一些处理,因此我需要以某种方式进行模拟,但是找不到解决方法。 I also want to point that tested method does not take this different class object as a parameter but is instantiating it within itself so it looks something like this: 我还想指出,经过测试的方法不会将这个不同的类对象作为参数,而是在自身内部实例化了它,因此它看起来像这样:

public class Class1 {
    public MyEnum method1(String myString){
        Class2 class2 = new Class2();
        return class2.method2(myString);
    }
}
public class Class2 {
    public MyEnum method2(String myString){
       //returns some value after communication with a server
    }
}

So basically I would need to mock method2 return value however as it's class is instantiated inside the method1 I can't see a way to do that. 所以基本上我需要模拟method2返回值,但是因为它的类是在method1内部实例化的,所以我看不到这样做的方法。 Is there any way of testing that without the actual server connection? 没有实际的服务器连接,是否有任何测试方法?

As a rule of thumb your unit test should test only one class, everything else should be mocked. 根据经验,您的单元测试应该只测试一个类,其他所有内容都应该被模拟。
As a rule of good design all dependencies should be injectable, ie your Class2 should not be instantiated inside your Class1 (and definitely not inside a method in this class as it creates a fresh instance every time the method is called). 作为良好设计的规则,所有依赖项都应该是可注入的,即,不应在Class1内部实例化Class2(并且绝对不要在此类的方法内部实例化,因为每次调用该方法都会创建一个新实例)。
If any of the above rules are broken you should consider rewriting the code. 如果以上任何规则被违反,则应考虑重写代码。

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

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