【问题标题】:Need help with writing test需要帮助编写测试
【发布时间】:2010-05-26 11:35:36
【问题描述】:

我正在尝试为这个名为 Receiver 的类编写一个测试:

public void get(People person) {
            if(null != person) {
               LOG.info("Person with ID " + person.getId() + " received");
               processor.process(person);
             }else{
              LOG.info("Person not received abort!");   
              }
        }

这是测试:

@Test
    public void testReceivePerson(){
        context.checking(new Expectations() {{          
            receiver.get(person);
            atLeast(1).of(person).getId();
            will(returnValue(String.class));        
        }});
    }

注意:receiver是Receiver类的实例(real not mock),processor是处理person的Processor类的实例(real not mock)(People类的mock对象)。 GetId 是 String 而不是 int 的方法,这不是错误的。

测试失败:意外调用 person.getId()

我正在使用 jMock 任何帮助将不胜感激。据我了解,当我调用此 get 方法以正确执行它时,我需要模拟 person.getId() ,并且我已经在圈子里狙击了一段时间,现在任何帮助将不胜感激。

【问题讨论】:

    标签: java unit-testing testing junit jmock


    【解决方案1】:

    如果我理解正确,你必须移动行receiver.get(person);在 context.checking 的范围之后 - 因为这是您的测试的执行,而不是设定期望。所以试试这个:

    @Test
    public void testReceivePerson(){
        context.checking(new Expectations() {{          
            atLeast(1).of(person).getId();
            will(returnValue(String.class));        
        }});
        receiver.get(person);
    }
    

    【讨论】:

    • 谢谢,同样的处理。我实际上解决了一个问题,我现在发布答案,我犯了几个错误。
    【解决方案2】:

    此外,您应该使用allow() 而不是atLeast(1),因为您在此处存根person 对象。最后,如果 Person 只是一个值类型,最好只使用类。

    【讨论】: