2

我正在尝试编写一个 Hamcrest 匹配器来验证返回 Class 对象的方法的返回值。例如,给定类:

public static class ClassHolder {
    private final Class clazz;

    public ClassHolder(Class clazz) {
        this.clazz = clazz;
    }

    public Class getClazz() {
        return clazz;
    }
}

我有一个测试,它创建了一个 Hamcrest 匹配器来匹配调用的结果getClazz()

public class LambdaJTest {
    @Test
    public void testClassHolder() {
        final ClassHolder classHolder = new ClassHolder(String.class);
        assertThat(classHolder, having(on(ClassHolder.class).getClazz(), is(String.class)));
    }
}

但是,此匹配器在执行时会引发异常:

ch.lambdaj.function.argument.ArgumentConversionException: It is not possible to create a placeholder for class: java.lang.Class
    at ch.lambdaj.function.argument.ArgumentsFactory.createArgumentPlaceholder(ArgumentsFactory.java:170)
    at ch.lambdaj.function.argument.ArgumentsFactory.createArgumentPlaceholder(ArgumentsFactory.java:156)
    at ch.lambdaj.function.argument.ArgumentsFactory.createPlaceholder(ArgumentsFactory.java:52)
    at ch.lambdaj.function.argument.ArgumentsFactory.registerNewArgument(ArgumentsFactory.java:45)
    at ch.lambdaj.function.argument.ArgumentsFactory.createArgument(ArgumentsFactory.java:39)
    at ch.lambdaj.function.argument.ProxyArgument.invoke(ProxyArgument.java:36)
    at ch.lambdaj.proxy.InvocationInterceptor.intercept(InvocationInterceptor.java:42)

有没有办法使用 LambdaJ 编写这样的匹配器?

4

1 回答 1

0

你不需要 lambdaj 来实现这一点。可以通过使用instanceOf 匹配器来做到这一点,如下所示:

assertThat(classHolder.getClazz(), Matchers.instanceOf(String.class)));

于 2011-10-16T21:02:01.860 回答