12

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"))));
    }


}
Community
  • 1
  • 1
k1eran
  • 4,492
  • 8
  • 50
  • 73

1 Answers1

20

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.

newacct
  • 119,665
  • 29
  • 163
  • 224
  • Note the compiler will enforce that `@SafeVarargs` is set on a **final** method, which is not possible of course on interfaces. – bric3 Jun 12 '15 at 17:05
  • 1
    I used `@SuppressWarnings("unchecked")` on the test method, but now I see another compiler warning `Unnecessary @SuppressWarnings("unchecked")`. How to get rid of this? – tarekahf Mar 10 '23 at 01:29