Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mocking Scala void function using Mockito

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.

like image 437
Barry Avatar asked Jun 05 '15 21:06

Barry


People also ask

Can you mock a void method?

Mockito provides following methods that can be used to mock void methods. doAnswer() : We can use this to perform some operations when a mocked object method is called that is returning void. doThrow() : We can use doThrow() when we want to stub a void method that throws exception.

Can you mock a Scala object?

ScalaMock is a native, open-source Scala mocking framework written by Paul Butcher that allows you to mock objects and functions.


1 Answers

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.

like image 149
marios Avatar answered Sep 21 '22 11:09

marios