How to taunt private recipients?

I have a class that I want to test. It looks something like 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(..); } } 

The Dependency1 class is complex, and I would like to mock it when writing a unit test for methodUnderTest() .

How to do it?

+6
source share
2 answers

It is very simple, and there is no need to mock a personal method or change the tested class:

 @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(); }} } 
+2
source

I think your architecture needs a search.

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 you can do the following:

 myClass.setDependency(realDependency); 

And in the test, you could:

 myClass.setDependency(mockDependency); 
+2
source

Source: https://habr.com/ru/post/987139/


All Articles