Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 941
Kevin Wong Avatar asked Sep 11 '08 15:09

Kevin Wong


People also ask

What is nice Mock?

createNiceMock() creates a mock and sets the default implementation of each method of the mock. If EasyMock. createMock() is used, then invoking the mock method throws assertion error.


1 Answers

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 } 
like image 51
Barend Avatar answered Sep 20 '22 01:09

Barend