Mocking Scala void function using Mockito
Asked Answered
C

1

7

I found a few answers for this but nothing is working for me.

Trying to mock Apache Shiro Subject interface login method which returns void.

Interface:

    void login(AuthenticationToken token) throws AuthenticationException;

I have tried :

   #1
  val subject = mock[Subject]
  doNothing().when(subject).login(new UsernamePasswordToken())

   #2
  val subject = mock[Subject]
  doNothing().when(subject).login(any[UsernamePasswordToken])

   #3
  when(subject.login(any[UsernamePasswordToken])).thenAnswer(new Answer[Void]() {
      override def answer(invocation: InvocationOnMock): Void = {
       null:Void
      }

I keep getting NullPointerException on login. My goal is test around the login method and test some success cases along with some failure cases where this method throws an exception.

Coruscate answered 5/6, 2015 at 21:40 Comment(6)
The default behavior in Mockito is to return nothing if you don't "stub" a particular method. That is, have you tried removing the whole `doDonthing()..." line?Annates
Yea so I did read something similar but leaving that line as mock(subject) was giving me NPECoruscate
Consider the () as [] typing on my phoneCoruscate
can you reproduce this into a short project? I am pretty sure Mockito is stubbing all methods by default. It shouldn't raise a NPE.Annates
Will do will also go back and I can post more code from method under test and test exception perhaps I read it wrongCoruscate
So you were correct mock[Subject] should have been fine because Mockito is stubbing all methods by default. The issue was higher up with how this projects test framework/utility classes were setup. The subject I was mocking was not the one fed to the request. So the code was using a different instantiated subject which is why it was going into actual implementation.Coruscate
A
10

The default behavior in Mockito is to return nothing if you don't "stub" a particular method. No need to force a void() function to doNothing() since it's doing nothing by default.

Annates answered 7/6, 2015 at 0:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.