Search code examples
javaunit-testingjunitjmockit

JMockit - warning when mocking methods that expect Collections


Is there a way to get the following mock to work without an Unchecked cast warning:

new Expectations() {{
        UrlService.addUrls((List<String>)any); result = expectedCandidates; 
}};

The UrlService.addUrls() method's signature is:

static List<Candidate> addUrls(List<String> urls)

Solution

  • The best alternative is to use the T witnAny(T arg) argument matcher:

    new Expectations() {{
        UrlService.addUrls(withAny(new ArrayList<String>()));
        result = expectedCandidates;
    }};
    

    Or, to disable the code inspection locally, if your IDE supports it. With IntelliJ, I can write:

    new Expectations() {{
        //noinspection unchecked
        UrlService.addUrls((List<String>) any);
        result = expectedCandidates;
    }};
    

    ... which really is OK. Code inspections are good and all, but there are always exceptional situations where it's fine to disable them.