Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Relax typing for the mocking result #229

henri-tremblay opened this issue Oct 21, 2018 · 0 comments

Relax typing for the mocking result #229

henri-tremblay opened this issue Oct 21, 2018 · 0 comments


Copy link

The typing to create a mock is <T> T mock(Class<T> c). This works perfectly with a normal type. But it doesn't work at all with a generic type.

For example, List<String> list = mock(List.class) will cause a unsolvable warning.

There are two solutions:
1- <T> T mock(TypeRef<T> ref) to allow 'List list = mock(new TypeRef<List>() {});
Here, TypeRef is a concrete class providing the generic type through ((ParameterizedType) getClass().getGenericSupertype()).getActualTypeArguments().

The drawbacks are that is requires the creation of an anonymous inner class every time. And it means a new set of mock() methods on the EasyMock class.

2- <T, R> R mock(Class<T> t) so the returned type is inferred from the left-hand side

The drawbacks are that in rare cases the inference won't work. Explicit typing will be required. And it means you can do List<String> list = mock(Integer.class)

I prefer number 2. It requires a typing change and that's it. Inference issues are pretty rare. The only current problem is with partial mocks. So they will keep the current typing but it might change if I find the right way to do it. Mocking the wrong type doesn't matter. It will throw an exception at the first execution.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
None yet

No branches or pull requests

1 participant