How about @SafeVarargs Mockito.reset(T...)?

465 views
Skip to first unread message

Róbert Papp

unread,
Jun 18, 2016, 6:00:47 AM6/18/16
to mockito
Hi Mockers!
Consider the following two simple repro classes:

interface Action<T> {
void act(T t);
}

class OnceExecutor<T> {
private final Action<T> action;
   public OnceExecutor(Action<T> action) {
this.action = action;
}
private boolean done;
   void exec(T param) {
if (done) {
return;
}
action.act(param);
done = true;
}
}

and the following tests

public class OnceExecutorTest {
@Test public void testActionExecuted() {
@SuppressWarnings("unchecked") Action<String> action = mock(Action.class);
OnceExecutor<String> executor = new OnceExecutor<>(action);

executor.exec("hello");

verify(action).act("hello");
}
@Test public void testActionExecutedOnlyOnce() {
@SuppressWarnings("unchecked") Action<String> action = mock(Action.class);
OnceExecutor<String> executor = new OnceExecutor<>(action);
executor.exec("hello");
// don't verify anything, that's done in testActionExecuted
reset(action); // forget anything happened

executor.exec("world"); // try to execute again

verifyZeroInteractions(action); // make sure it didn't act on action
}
}

I believe this is a justified case of using reset(). Imagine that a single verification is more complex that the simple act("hello") in testActionExecuted.

My problem with this is that I get an unchecked generic array creation warning:

which I believe is unnecessary in case of Mockito.reset, especially calling with a single argument.

What do you think about adding a @SafeVarargs annotation to reset? If I add this method to my test class the unchecked warning disappears:
@SafeVarargs public static <T> void reset(T... mocks) {
Mockito.reset(mocks);
}
so doing the same in Mockito would get rid of all unchecked warnings for all users. I really don't like suppressing warnings broadly (broader than variable decl) because it could hide bugs in the code that would otherwise be noticed.

An alternative is to simply get rid of the <T> on reset and clearInvokations and so all the varargs methods have similar signatures (see ignoreStubs, verifyNoMoreInteractions, verifyZeroInteractions, inOrder).

+Robi
Reply all
Reply to author
Forward
0 new messages