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

喜你入骨 提交于 2019-12-31 17:37:49

问题


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>".


回答1:


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
}



回答2:


I worked around this problem by introducing a subclass, e.g.

private abstract class MySpecialString implements MySpecial<String>{};

Then create a mock of that abstract class:

MySpecial<String> myMock = createControl().createMock(MySpecialString.class);



回答3:


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.)




回答4:


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



回答5:


I know this goes against the question, but why not create a List rather than a Mock List?

It's less code and easier to work with, for instance if you want to add items to the list.

MyItem myItem = createMock(myItem.class);
List<MyItem> myItemList = new ArrayList<MyItem>();
myItemList.add(myItem);

Instead of

MyItem myItem = createMock(myItem.class);
@SuppressWarnings("unchecked")
List<MyItem> myItemList = createMock(ArrayList.class);
expect(myItemList.get(0)).andReturn(myItem);
replay(myItemList);


来源:https://stackoverflow.com/questions/56954/easymock-how-do-i-create-a-mock-of-a-genericized-class-without-a-warning

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!