【问题标题】:How to return type I explicitly passed as parameter?如何返回我作为参数显式传递的类型?
【发布时间】:2013-07-15 15:11:55
【问题描述】:

我想将一个类型存储为参数,但是当我返回它并在 JUnit 测试中签入时,我得到类似

Expected: an instance of Java.lang.String
but: <class java.lang.String> is a java.lang.class

这是该类的最小化示例...

public class ContextVariableResult<T> {
    private Class<T> type;

    public ContextVariableResult(Class<T> type) {
        this.type = type;
    }

    //TODO doesn't work
    public Class<T> getType() {
        return type;
    }
}

我将 String.class 作为构造函数参数传递。

我的测试看起来像这样......

assertThat(result.getType(), instanceOf(String.class));

我认为我的 hamcrest 匹配器是错误的,但由于编译错误,我无法使用 is(String.class)isA(String.class)

 The method assertThat(T, Matcher<? super T>) in the type Assert is not applicable for the arguments (Class<capture#3-of ?>, 
     Matcher<String>)

我已经尝试返回反射对象Type,我也尝试强制转换为ParameterizedType,但后来我得到ClassCastExceptions等等。

我希望方法结果是“字符串”。我做错了什么?如果我不需要传递参数“String.class”会好很多,但是我想我总是遇到类型擦除问题。

【问题讨论】:

    标签: java generics types hamcrest


    【解决方案1】:

    您正在检查返回值是否是字符串的实例,例如"hello"。但是你的方法返回类String,即String.class

    我猜你的方法返回了你想要的。在这种情况下,您甚至不必使用hamecrest 进行验证。常规的JUnitAssert.assertEquals(String.class, result.getType()) 会为您工作。

    【讨论】:

      【解决方案2】:

      你写的课很好。您的测试不正确,因为Class&lt;String&gt; 不是String 的实例。更改断言:

      assertThat(result.getType(), is(String.class));
      // or
      assertEquals(String.class, result.getType());
      

      【讨论】:

      • assertEquals 有效,但是当我尝试使用第一个时,Eclipse 告诉我The method assertThat(T, Matcher&lt;? super T&gt;) in the type Assert is not applicable for the arguments (Class&lt;capture#4-of ?&gt;, Matcher&lt;String&gt;)
      猜你喜欢
      • 2014-05-13
      • 2021-04-02
      • 1970-01-01
      • 2021-02-12
      • 1970-01-01
      • 1970-01-01
      • 2012-11-25
      • 2021-03-25
      相关资源
      最近更新 更多