> On May 8, 2020, at 1:08 PM, Kirk Lund <kl...@apache.org> wrote:
> 
> Actually there is an alternative to using @SuppressWarnings for Mockito
> mocks:
> 
> Region<String, String> region = cast(mock(Region.class));
> 
> private static <T> T cast(Object object) {
>  return (T) object;
> }

The cast method will need to suppress unchecked warnings.

You will need:

protected Region<String, HttpSession> region = cast(mock(Region.class));

@SuppressWarnings("unchecked")
private static <T> T cast(Object object) {
  return (T) object;
}

Or:

@SuppressWarnings("unchecked")
protected Region<String, HttpSession> region = mock(Region.class);

I think the latter is more readable and identifies the intent do an unchecked 
cast here.


Alternatively:

import static Casts.unchecked;
...
protected Region<String, HttpSession> region = 
uncheckedCast(mock(Region.class));
…

class Casts {
  @SuppressWarnings("unchecked”)
  private static <T> T uncheckedCast(Object object) {
    return (T) object;
  }
}

Is nice because it gives the reader the information that an intentional uncheck 
cast is happening here but hides the suppression annotation elsewhere.

The point being I shouldn’t see warnings when compiling code, that smells of 
bad. If you intentionally need to do something the compiler does not understand 
and warns about then make the intent readable. 

-Jake

Reply via email to