Question

I want to store a type as parameter, but when I return it and check in within a JUnit test, I get something like

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

This is a minimalized example of the 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;
    }
}

I pass String.class as constructor parameter.

My test looks like this....

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

I thought that my hamcrest matcher is wrong, but I can't use is(String.class) or isA(String.class) due to compilation errors:

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

I already tried to return the reflection object Type, I also tried to cast to ParameterizedType, but then I get ClassCastExceptions and so on.

I want the method result to be "String". What did I wrong? It would be much better if I don't need to pass the parameter "String.class", but then I think I always get type erasure problems.

Was it helpful?

Solution

You are checking that the return value is instance of string, e.g. "hello". But your method return class String, i.e. String.class.

I guess that your method returns what you wanted. In this case you even do not have ot use hamecrest for your validation. The regular JUnit's Assert.assertEquals(String.class, result.getType()) will work for you.

OTHER TIPS

The class you've written is fine. Your test is incorrect, because a Class<String> is not an instance of String. Change the assertion:

assertThat(result.getType(), is(String.class));
// or
assertEquals(String.class, result.getType());
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top