devmao
devmao

Reputation: 680

EasyMock: Method with a callback argument

I have a situation like this:

class A {
  void methodA(Callback cb) {
    ...
    cb.onResult(result);
  }
}

class B {
  void methodB(A a) {
    a.methodA(new Callback() {
      void onResult(Result r) {
        ...
      }
    });
  }
}

and the question is: How can I test the "B.methodB" with different "result" with EasyMock?

Upvotes: 1

Views: 1309

Answers (2)

Ian Roberts
Ian Roberts

Reputation: 122364

You could capture the Callback that is passed to methodA

Capture<Callback> cap = new Capture<Callback>();
mockA.methodA(capture(cap));
replay(mockA);
instanceOfB.methodB(mockA);
Callback cb = cap.getValue();

// now we can call cb.onResult with a mocked Result instance

Upvotes: 2

Paul Grime
Paul Grime

Reputation: 15104

Can you refactor to make it easier to test?

class B {
  void methodB(A a) {
    a.methodA(new Callback() {
      void onResult(Result r) {
        onResultFromA(r);
      }
    });
  }
  void onResultFromA(Result r) {
  }
}

Then just test onResultFromA()?

You don't really care where r comes from, just that you do the right thing with it?

Or do you?

Upvotes: 1

Related Questions