After clarification in the comments
If it is inherited, you can use the last template I proposed (test extends myClass) and simply override the Call () method
In this answer, I assume that the Call () method is a non-stationary method of another class that you have.
allows you to change the example code:
import whatever.package; Class myClass { public void myMethod() { ... anotherClass aClass = new anotherClass(); int a = aClass.methodCall(); ... } }
So now we want to make fun of anotherClassCall () method.
The usual procedure is to use interfaces and push the โwiringโ to another location to avoid hard communication. Do some research on dependency injection and similar concepts.
In short, using new anotherClass () creates a tight connection. You could add anotherClass object to myClass constructor or through getters and seters. I assume you need to mock writing unit tests. Consider the following code:
import whatever.package; Class myClass { private IanotherClass another; public void SetAnotherClass(IAnotherClass aClass) { another = aClass; } public void myMethod() { ... int a = another.methodCall(); ... } }
Test code:
myClass testedClass = new myClass(); testedClass.SetAnotherClass(new MyAnotherClassMock()); testedClass.myMethod();
As for dependency injection and programming against interfaces, not implementations, you can read them on this topic - just google it!
If you donโt want to reconfigure all your code and just need a quick (and a bit dirty) fix, you might consider moving the instance of anotherClass to separate methods, and then just ask your test classes to inherit from your class, overwriting the methods mentioned (this is not always possible - it all depends on your actual code)
example:
Class myClass { public void myMethod() { ... IanotherClass aClass = GetAnotherClassInstance(); int a = aClass.methodCall(); ... } protected IanotherClass GetAnotherClassInstance() { return new anotherClass(); } } Class MyTestClass extends myClass { @overwrite protected IanotherClass GetAnotherClassInstance() { return new anotherClassMock(); } }
Then just use myTestClass for your test!