Reputation: 1436
The class structures are as follows:
public interface Sender {
void send(String note);
}
public interface Agent {
void sendNote(String note);
}
public class Emailer implements Sender {
void send(String note) {
//...do something
}
}
public class EmailAgent implements Agent {
void sendNote(String note) {
Sender sender = new Emailer();
sender.send();
}
}
I have implemented my JMock/JUnit test like this:
@Rule
public JUnitRuleMockery context = new JUnitRuleMockery();
Sender sender = context.mock(Sender.class);
@Test
public void test1() {
context.checking(new Expectations() {{
exactly(1).of(sender).send("test");
}});
new EmailAgent().sendNote("test");
}
For some reasons, the above is failing because it said sender.send()
is never invoked. How is this possible?
Upvotes: 0
Views: 76
Reputation: 43391
EmailAgent doesn't use a Sender that it gets from anywhere; it creates its own. So:
sendNote
, which creates a second Sender (call it "b").send
invoked -- which it didn't, since the EmailClient didn't know about it.Rather than creating a Sender within EmailAgent.sendNote
, you should create a constructor in EmailAgent that takes a Sender and stores it in an instance field, and then uses that field in sendNote
. Then, the test passes its mocked sender to the EmailAgent.
Upvotes: 1