简体   繁体   English

类参数的easymock方法匹配器

[英]easymock method matcher for class argument

I have a method with signature as follows: 我有一个签名方法如下:

    public <T extends S> T foo(final Class<T> clazz){
       .....
       .....
    }

How do I mock this method in easymock? 如何在easymock中模拟此方法?

I tried following two lines in my test class but still the expected object is not returned, so I get NullPointerException. 我尝试在测试类中遵循以下两行,但仍未返回预期的对象,因此我得到了NullPointerException。

    Capture<Class<MyClass>> classCapture = new Capture<Class<MyClass>>();
            expect(someObject.foo(EasyMock.capture(classCapture))).andReturn(testObject);

And testObject is initialized in the test class, which I want to get returned when 并且testObject在测试类中初始化,我想在

    foo() 

is called. 叫做。 Where am I doing wrong? 我在哪里做错了?

I'm not sure why you want to capture the variable in this instance, but your problem is the way you typed your command means you are looking for a method foo() without any arguments. 我不确定为什么要在此实例中捕获变量,但是问题是键入命令的方式意味着您正在寻找不带任何参数的方法foo()

You need to you need to use and() to chain the capture and the argument matcher requirements for the method call: 您需要使用and()链接方法调用的捕获和参数匹配器要求:

expect(someObject.foo(EasyMock.and(
                            EasyMock.capture(classCapture),
                            anyObject()))
                      )
            .andReturn(testObject);

Then after you call your mock in replay mode you can get the captured argument back with capture.getValue() 然后,在重播模式下调用模拟之后,您可以使用capture.getValue()返回已捕获的参数。

    replay(someObject);

    assertSame(testObject, someObject.foo(MyClass.class));

    assertEquals(MyClass.class, classCapture.getValue());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM