【问题标题】:How do I expect and verify the same method in JMockit我如何期望和验证 JMockit 中的相同方法
【发布时间】:2013-09-18 09:29:17
【问题描述】:

具有以下类:

class ToTest{
    @Autowired
    private Service service;

    public String make(){
         //do some calcs
         obj.setParam(param);
         String inverted = service.execute(obj);
         return "<" + inverted.toString() + ">";
    }
}

我想添加一个测试,它断言 service.execute 是使用带有参数 X 的对象调用的。

我会通过验证来做到这一点。我想模拟这个调用并让它返回一些可测试的东西。我这样做是有期望的。

@Tested
ToTest toTest;
@Injected
Service service;

new NonStrictExpectations(){
   {   
       service.exceute((CertainObject)any)
       result = "b";
   }
};

toTest.make();

new Verifications(){
   {   
       CertainObject obj;
       service.exceute(obj = withCapture())
       assertEquals("a",obj.getParam());
   }
};

我在 obj.getParam() 上得到一个空指针。显然验证不起作用。如果我消除预期它会起作用,但我会在inverted.toString() 中得到一个空指针。

你们将如何完成这项工作?

【问题讨论】:

    标签: java spring testing mocking jmockit


    【解决方案1】:

    使用 JMockit 1.4,以下测试类对我来说工作正常:

    public class TempTest
    {
        static class CertainObject
        {
            private String param;
            String getParam() { return param; }
            void setParam(String p) { param = p; }
        }
    
        public interface Service { String execute(CertainObject o); }
    
        public static class ToTest
        {
            private Service service;
    
            public String make()
            {
                CertainObject obj = new CertainObject();
                obj.setParam("a");
                String inverted = service.execute(obj);
                return "<" + inverted + ">";
            }
        }
    
        @Tested ToTest toTest;
        @Injectable Service service;
    
        @Test
        public void temp()
        {
             new NonStrictExpectations() {{
                 service.execute((CertainObject) any);
                 result = "b";
             }};
    
             toTest.make();
    
             new Verifications() {{
                 CertainObject obj;
                 service.execute(obj = withCapture());
                 assertEquals("a", obj.getParam());
             }};
        }
    }
    

    你能展示一个失败的完整示例测试吗?

    【讨论】:

    • 我只是在使用旧版本的 JMockit。
    • 此代码不再适用于 JMockit 1.23 版。我会得到以下异常:java.lang.IllegalStateException:已经记录了相同的期望;请删除此验证或调整记录...原因:冗余期望...定义期望并进行一些自定义验证的推荐方法是什么?
    • 在上面的测试中可以使用四种不同的机制,都在期望记录块中,删除了验证块:1) 使用在调用 withArgThat(Hamcrest matcher) 时传递的 Hamcrest 参数匹配器; 2) 在对with(Delegate) 的调用中使用自定义匹配器; 3) 使用withCapture(List); 4) 为result 分配一个Delegate 对象,该对象验证接收到的参数。其中哪一个是最好的取决于几个因素,包括个人喜好。当然,示例测试实际上并不需要这个,因为它只是检查参数是"a"
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多