Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mock private getters? [duplicate]

Tags:

java

jmockit

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?

like image 630
lg.lindstrom Avatar asked May 13 '15 13:05

lg.lindstrom


People also ask

Can private methods be mocked?

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.

How to mock a method using Mockito?

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.

What is@ mock in junit?

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.

What is Mockito stubbing?

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.


Video Answer


2 Answers

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(); }}
}
like image 161
Rogério Avatar answered Sep 27 '22 19:09

Rogério


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);
like image 43
NickJ Avatar answered Sep 27 '22 20:09

NickJ