【问题标题】:JMock - Object without expectationJMock - 没有期望的对象
【发布时间】:2013-10-27 23:57:26
【问题描述】:

我正在使用 junt 和 jock。 假设我的测试类中有一个对象接口Contact 和一个类似这样的方法:

@Test
public void testAddOneContact() {
    final Contact contact = this.context.mock(Contact.class);

    this.addressBook.addContact(contact);

    assertTrue("Object added to list", this.addressBook.getNumberOfContacts() == 1);        
} 

方法addContact是这样实现的:

public void addContact(Contact contact) {

    //Check if contact passed is valid. If it is, add it to address book
    if(contact != null) {
        this.contactsList.add(contact);
    }
}

所以你可以看到我没有调用Contact 接口的任何方法。 为此,我不能对测试方法testAddOneContact()抱有任何期望。 这是实现测试用例和使用 JMock 的正确方法吗(所以即使我没有任何期望)?

【问题讨论】:

    标签: java junit junit4 jmock


    【解决方案1】:

    我会试一试:。

    首先,我看不出你写测试的方式有什么不妥。

    根据测试用例描述,我假设测试用例用于存储联系人列表的 AddressBook 类,并且您正在测试 addContact 公开的方法AddressBook 类。

    也就是说,您仍然可以通过在 addContact 方法中执行以下操作来使您的类更加健壮:

    public void addContact(Contact contact) throws IllegalArgumentException
    {
        if(contact == null)
        {
               //throw an exception after logging that contact is null
               throw new IllegalArgumentException("Passed in contact cannot be null!!")
        }
        this.contactsList.add(contact);
    }
    

    现在您的 testAddOneContact 测试代码必须测试两个不同的输入用例,这可以使用两个单独的测试用例如下完成

    @Test
    public void testAddOneContact() {
        final Contact contact = this.context.mock(Contact.class);
    
        this.addressBook.addContact(contact);
    
        assertTrue("Object added to list", this.addressBook.getNumberOfContacts() == 1);  
    
        //assuming that Contact class implements the equals() method you can test that the contact
        //added is indeed the one that you passed in
        assertTrue(addressBook.get(0).equals(contact));      
    }
    
    
    
    //the below test ensures that there is exception handling mechanism within your library code
    @Test
    @Expected(IllegalArgumentException.class)
    public void testShouldThrowWhenContactIsNull()
    {
        this.addressBook.addContact(null);
    }
    

    顺便说一句 - 请注意实现一个好的测试类如何让您考虑如何设计要公开为 API 的方法,以及如何需要覆盖 hashCodeequals() 等某些方法。它也让你思考 - “我如何处理错误情况?”。这些深思熟虑的问题对于确保您发布的代码能够准确地解决它应该以高效且无错误的方式解决的问题至关重要。

    希望对你有帮助

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-14
      • 1970-01-01
      相关资源
      最近更新 更多