7

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?

UrsinusTheStrong
  • 1,239
  • 1
  • 16
  • 33
lg.lindstrom
  • 776
  • 1
  • 13
  • 31
  • it's sufficiently different to keep open, IMO – NickJ May 13 '15 at 14:35
  • @NickJ: I'm not as convinced it is. The advice is going to be generally the same: don't do it, use a different approach to inject those dependencies, etc. – Makoto May 13 '15 at 15:44

2 Answers2

2

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);
NickJ
  • 9,380
  • 9
  • 51
  • 74
2

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(); }}
}
Rogério
  • 16,171
  • 2
  • 50
  • 63