Mocking a Source in Akka Streams

Viewed 196

I have a wrapper class AwsS3Bucket which when invoked, returns a source Source[ByteString, NotUsed]. In my unit test case, I have mocked this client and do the necessary assertions.

val source = Source.fromIterator(() => List(ByteString("some string")).toIterator)
when(awsS3Bucket.getSource(any[String])).thenReturn(source)

However, now I want to test the error scenario wherein I want the getSource method to throw an exception. I tried the following code,

val error = new RuntimeException("error in source")
when(awsS3Bucket.getSource(any[String])).thenReturn(error)

but it gives me a compilation issue saying that

Cannot resolve overloaded method thenReturn

Can anyone please let me know the correct method of returning an exception in a Source in akka streams.

1 Answers

You have to use thenThrow(new RuntimeException("error in source")) to stub an Exception.

That said, you may find issues sometimes with checked exceptions as Scala treats all exceptions as runtime, so they aren't declared in the signature, and standard Mockito will validate you're stubbing an exception that can be thrown by the stubbed method.

In mockito-scala that check has been removed to acknowledge the fact that all exceptions behave as runtime in Scala

Related