xcoder
xcoder

Reputation: 1436

Why this JMock test is failing?

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

Answers (1)

yshavit
yshavit

Reputation: 43391

EmailAgent doesn't use a Sender that it gets from anywhere; it creates its own. So:

  • Ihe test creates a mocked Sender (call it "a").
  • It then invokes sendNote, which creates a second Sender (call it "b").
  • That method returns, and the test then checks that "a" had 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

Related Questions