Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Unchecked generic array creation for varargs parameter of type Matcher <? extends String> []" warning using CoreMatchers.allOf()

In my UT code, extract below, I see warning :

Unchecked generic array creation for varargs parameter of
type Matcher <? extends String> []

I have read in another stackoverflow answer about the problems using a generic parameter to a varargs method.

But is there a neat way to slightly restructure this test to get rid of the ugly warning and avoid @SuppressWarnings?

package stackoverflow;

import org.hamcrest.CoreMatchers;
import org.junit.Assert;
import org.junit.Test;
import static org.junit.matchers.JUnitMatchers.containsString;
import static org.hamcrest.CoreMatchers.not;

public class FooTest {


    @SuppressWarnings({"unchecked"})
    @Test
    public void sampleTest() {

        Assert.assertThat("foo bar",
                CoreMatchers.allOf(
                containsString("foo"),
                containsString("bar"),
                not(containsString("baz"))));
    }


}
like image 415
k1eran Avatar asked Jul 16 '13 14:07

k1eran


1 Answers

If this is Java 7+, then the library you're using can annotate the method with @SafeVarargs. However, this is not under your control.

Otherwise there is no way to avoid an unchecked warning with this method, because the method fundamentally requires an array of a parameterized type, and it is impossible to obtain a non-null value of this type without an unchecked operation somewhere (either in your method or some other method that you call).

Or, looking at the documentation for CoreMatchers, it seems that you could consider using the alternate overload of the allOf, which takes an Iterable of matchers instead. That you can use without unchecked operations.

like image 120
newacct Avatar answered Nov 15 '22 14:11

newacct