mockito / mockito

Most popular Mocking framework for unit tests written in Java
http://mockito.org
MIT License
14.88k stars 2.56k forks source link

Unhelpful error message when trying to mock final method when similar non-final method exists #1140

Open dbarwacz opened 7 years ago

dbarwacz commented 7 years ago

Suppose we mock java class java.util.Calendar. There is a public final Date getTime method and public long getTimeInMillis. When trying to mock the earlier, I get message:

org.mockito.exceptions.misusing.WrongTypeOfReturnValue: 
Date$MockitoMock$282612676 cannot be returned by getTimeInMillis()
getTimeInMillis() should return long
***
If you're unsure why you're getting above error read on.
Due to the nature of the syntax above problem might occur because:
1. This exception *might* occur in wrongly written multi-threaded tests.
   Please refer to Mockito FAQ on limitations of concurrency testing.
2. A spy is stubbed using when(spy.foo()).then() syntax. It is safer to stub spies - 
   - with doReturn|Throw() family of methods. More in javadocs for Mockito.spy() method.

For some reason, mockito is trying to apply similar method (or run final code?) while it should probably detect that it's used to mock final method. Mockito version used: 2.8.9, environment: android.

TimvdLippe commented 7 years ago

Could you update your issue description with a minimal reproduction case? That way I can run it and check out the exception.

dbarwacz commented 7 years ago

Sorry, I was describing issue instead of copying a few lines' test case I already had.

tested method:

import java.text.SimpleDateFormat;
import java.util.Calendar;

private final Calendar calendar;
private final SimpleDateFormat dateFormat;

public String formatRemainingSeconds(int tickCount) {
  calendar.clear();
  calendar.set(Calendar.SECOND, tickCount);
  return dateFormat.format(calendar.getTime());
}

test code:

@Test
public void testFormatRemainingSeconds() throws Exception {
  Date date = mock(Date.class);
  when(calendar.getTime()).thenReturn(date);
  when(dateFormat.format(date)).thenReturn("result");

  String result = tested.formatRemainingSeconds(10);

  InOrder inOrder = inOrder(calendar);
  inOrder.verify(calendar).clear();
  inOrder.verify(calendar).set(Calendar.SECOND, 10);
  inOrder.verify(calendar).getTime();

  verify(dateFormat).format(date);

  assertEquals("result", result);
}
antlechner commented 6 years ago

Are there any updates about this bug? I'm having the same problem (same error message when trying to mock Calendar.getTime) with Mockito version 1.10.19 and Powermock version 1.6.5. I know those versions are quite old but I haven't been able to get Powermock to work with recent versions of Mockito yet.

mockitoguy commented 6 years ago

We don’t have capacity to support Powermock. Sorry about the inconvenience!