Home > Enterprise >  Mocking objects from a constructor parameter
Mocking objects from a constructor parameter

Time:04-02

I have the following class layouts:

public class Service {
  ServiceHelper helper;
  ...class methods...
}

public class ServiceHelper {
  Foo foo;
  Bar bar;
...class methods...
}

I am creating a unit test for Service, but I want to use ServiceHelper as a "live" class, but the constructor parameters inside the ServiceHelper to be mocked. Is there a way to achieve this via Mockito?

CodePudding user response:

I think your example is not a good practice. Unit testing should be as small as possible. The goal of unit testing is to isolate each part of the program and show that the individual parts are correct.

Anyway, you still can try this approach. I hope it helps.

public class Service {

  private ServiceHelper helper;

  public Service(ServiceHelper helper) {
    this.helper = helper;
  }
}

public class ServiceHelper {

  private Foo foo;
  private Bar bar;

  // for unit testing only
  ServiceHelper(Foo foo, Bar bar) {
    this.foo = foo;
    this.bar = bar;
  }
}

And the test class :

public class ServiceTest {

  @Test
  public void your_test() {
    // arrange
    Foo mockedFoo = mock(Foo.class);
    Bar mockedBar = mock(Bar.class);
    ServiceHelper helper = new ServiceHelper(mockedFoo, mockedBar);  // the 'live' class
    Service service = new Service(helper);

    // act
    service.doSomething();

    // your assert ...
  }
}
  • Related