【问题标题】:Why this JMock test is failing?为什么这个 JMock 测试失败了?
【发布时间】:2016-02-16 09:00:11
【问题描述】:

类结构如下:

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();
    }
}

我已经像这样实现了我的 JMock/JUnit 测试:

@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");
}

由于某些原因,上面的代码失败了,因为它说sender.send() 从未被调用过。这怎么可能?

【问题讨论】:

  • 您的new EmailClient() 对模拟sender 对象一无所知。如果您将它传递给方法,无论是通过构造函数还是方法本身,它都会按照您的意愿行事。相反,您在测试类中创建模拟 sender 并在 test1 方法中创建另一个模拟。

标签: java jmock


【解决方案1】:

EmailAgent 不使用从任何地方获取的 Sender;它创造了自己的。所以:

  • 我的测试创建了一个模拟的发件人(称之为“a”)。
  • 然后它调用sendNote,创建第二个发件人(称为“b”)。
  • 该方法返回,然后测试检查“a”是否调用了 send - 它没有调用,因为 EmailClient 不知道。

您不应在EmailAgent.sendNote 中创建发件人,而应在EmailAgent 中创建一个构造函数,该构造函数接受一个发件人并将其存储在实例字段中,然后在sendNote 中使用该字段。然后,测试将其模拟的发件人传递给 EmailAgent。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-02-09
    • 1970-01-01
    • 1970-01-01
    • 2021-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-31
    相关资源
    最近更新 更多