user1325378
user1325378

Reputation: 89

How to mock a downstream method call?

I have an issue where I have some code like

public void a() { 
    Obj1 one = Obj1();
    Obj2 two = Obj2();
    one.b();
    two.c();
}

I'm trying to call the a() method, and I would like the b() method to execute but I would like to mock out the c() method.

What is the best way to do this, since Obj2 two gets declared within a()?

Upvotes: 1

Views: 878

Answers (2)

Rogério
Rogério

Reputation: 16380

Here is a working example test, using the JMockit library (which I develop):

@Test
public void exampleTest(@Mocked Obj2 anyObj2) {
    new A().a();

    // In case we want to check two.c() was called:
    new Verifications() {{ anyObj2.c(); }};
}

Upvotes: 0

GhostCat
GhostCat

Reputation: 140457

Two options:

  • you rework your design to become easier to test. For example by getting rid of that that new Obj2() call. Instead, you could pass a factory for Obj2 objects to that class; and use that. The factory returns mocked objects; you are fine. Or you look into other mechanisms for dependency injection.
  • you turn to PowerMock(ito) which allows for mocking calls to new; as outlined here for example.

My personal two cent: I recommend to go for option 1 - it is always better to improve the design; instead of using the big (ugly) PowerMock hammer to "fix" design problems. So, a simple example would like:

public class EnclosingClass {
  private final Obj2Factory factory;
  EnclosingClass(Obj2Factory factory) {
    this.factory = factory;
  }
 void a() {
   Ob2 two = factory.make();
 }

Upvotes: 1

Related Questions