xenoterracide
xenoterracide

Reputation: 16837

How do I use Mockito.doReturn in 2.7.x

Mockito version: v2.7.5/19.

The exception:

org.mockito.exceptions.misusing.UnfinishedStubbingException: 
Unfinished stubbing detected here:
-> at com.mckesson.dex.dao.code.CodeDaoMockTest.testExcluded(CodeDaoMockTest.java:33)

E.g. thenReturn() may be missing.
Examples of correct stubbing:
    when(mock.isOk()).thenReturn(true);
    when(mock.isOk()).thenThrow(exception);
    doThrow(exception).when(mock).someVoidMethod();
Hints:
 1. missing thenReturn()
 2. you are trying to stub a final method, which is not supported
 3: you are stubbing the behaviour of another mock inside before 'thenReturn' instruction if completed

here's my code:

@RunWith(MockitoJUnitRunner.class)
public class CodeDaoMockTest
{
    @Mock( name = "entityManager") private HibernateEntityManager entityManager;
    @Spy @InjectMocks
    private CodeDao dao;

    @Test
    public void testExcluded() throws Exception
    {

        LabTestClassification ltc1 = new LabTestClassification();
        LabTestClassification ltc2 = new LabTestClassification();

        Mockito.doReturn( 533965, 533966)
            .when( dao.getNextCodeIntegerFromSequence( ltc1  ) );

it's worth noting that if I write this:

Mockito.when( dao.getNextCodeIntegerFromSequence( ltc1  ) ).thenReturn( 533965 );

I get a null pointer on a call to entityManager. My understanding is if I use doReturn then the actual getNext... will never be called, which is the goal.

Upvotes: 1

Views: 866

Answers (1)

Maciej Kowalski
Maciej Kowalski

Reputation: 26512

You were close. Try with a bit different syntax:

Mockito.doReturn(533965).when(dao).getNextCodeIntegerFromSequence(ltc1);

Here is an article I wrote on Mockito Stubbing if you need a further read.

Upvotes: 4

Related Questions