I have a class that I want to test. It looks similar to this:
public class ClassUnderTest
{
private Dependency1 dep1;
private Dependency1 getDependency1()
{
if (dep1 == null)
dep1 = new Dependency1();
return dep1;
}
public void methodUnderTest()
{
.... do something
getDependency1().InvokeSomething(..);
}
}
Class Dependency1 is complex and I would like to mock it out when writing a unit test for methodUnderTest()
.
How do I do that?
For Mockito, there is no direct support to mock private and static methods. In order to test private methods, you will need to refactor the code to change the access to protected (or package) and you will have to avoid static/final methods.
With Mockito, you create a mock, tell Mockito what to do when specific methods are called on it, and then use the mock instance in your test instead of the real thing. After the test, you can query the mock to see what specific methods were called or check the side effects in the form of changed state.
While doing unit testing using junit you will come across places where you want to mock classes. Mocking is done when you invoke methods of a class that has external communication like database calls or rest calls.
A stub is a fake class that comes with preprogrammed return values. It's injected into the class under test to give you absolute control over what's being tested as input. A typical stub is a database connection that allows you to mimic any scenario without having a real database.
It's very easy, and there is no need to mock a private method or change the class under test:
@Test
public void exampleTest(@Mocked final Dependency dep) {
// Record results for methods called on mocked dependencies, if needed:
new Expectations() {{ dep.doSomething(); result = 123; }}
new ClassUnderTest().methodUnderTest();
// Verify another method was called, if desired:
new Verifications() {{ dep.doSomethingElse(); }}
}
I think your architecture needs looking at.
Why not do something like this...
public class MyClass {
private Dependency dependency;
public void setDependency(Dependency dep) {
this.dependency = dep;
}
public void myMethod() {
Result result = dependency.callSomeMethod();
//do stuff
}
}
Then in production you could do:
myClass.setDependency(realDependency);
And in test, you could:
myClass.setDependency(mockDependency);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With