Monday, March 7, 2011

EasyMock: How do I create a mock of a genericized class without a warning?

The code

private SomeClass<Integer> someClass;
someClass = EasyMock.createMock(SomeClass.class);

gives me a warning "Type safety: The expression of type SomeClass needs unchecked conversion to conform to SomeClass<Integer>".

From stackoverflow
  • The two obvious routes are to suppress the warning or mock a subclass.

    private static class SomeClass_Integer extends SomeClass<Integer>();
    private SomeClass<Integer> someClass;
    ...
        someClass = EasyMock.createMock(SomeClass_Integer.class);
    

    (Disclaimer: Not even attempted to compile this code, nor have I used EasyMock.)

    bmatthews68 : The syntax should probably be: private static interface SomeClass_Integer extends SomeClass {} I have the same problem and this is the work around I use so the approach will work. But I hope somebody has the answer we are looking for
  • You can annotate the test method with @SuppressWarnings("unchecked"). I agree this is some what of a hack but in my opinion it's acceptable on test code.

    @Test
    @SuppressWarnings("unchecked")
    public void someTest() {
        SomeClass<Integer> someClass = EasyMock.createMock(SomeClass.class);
    }
    
    Kevin Wong : yeah, but that leaves me feeling cheap
    SamBeran : If you go this route (hopefully there is a better way), much better to put the @SuppressWarnings on the variable assignment rather than the whole method.
  • AFAIK, you can't avoid the unchecked warning when a class name literal is involved, and the SuppressWarnings annotation is the only way to handle this.

    Note that it is good form to narrow the scope of the SuppressWarnings annotation as much as possible. You can apply this annotation to a single local variable assignment:

    public void testSomething() {
    
        @SuppressWarnings("unchecked")
        Foo<Integer> foo = EasyMock.createMock(Foo.class);
    
        // Rest of test method may still expose other warnings
    }
    

    or use a helper method:

    @SuppressWarnings("unchecked")
    private static <T> Foo<T> createFooMock() {
        return (Foo<T>)EasyMock.createMock(Foo.class);
    }
    
    public void testSomething() {
        Foo<String> foo = createFooMock();
    
        // Rest of test method may still expose other warnings
    }
    

0 comments:

Post a Comment