Arkadeusz91
Arkadeusz91

Reputation: 89

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. Is there any way of testing that without the actual server connection?

Upvotes: 0

Views: 352

Answers (1)

Germann Arlington
Germann Arlington

Reputation: 3353

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, i.e. 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).
If any of the above rules are broken you should consider rewriting the code.

Upvotes: 1

Related Questions