1
votes

I'm trying to mock the RabbitMQ ConnectionFactory object to return a mocked connection, using scalatest and mockito. Below is an example test that I am using:

class RabbitMQMockTest extends FunSuite with MockitoSugar {
    test("RabbitMQ ConnectionFactory is correctly mocked") {
        def connectionFactory = mock[ConnectionFactory]
        def connection = mock[Connection]

        when(connectionFactory.newConnection()).thenReturn(connection)
        println(connectionFactory.newConnection())

        assert(connectionFactory.newConnection() != null)
    }
}

This always fails and the println statement always prints "null". I am very new to using these technologies together and was wondering if anyone had any advice or could let me know if I'm doing anything wrong. Thanks in advance!

2
Can you break up your test to only rely on the mock Connection? It's generally nasty to mock multiple levels of dependencies this way -- you'll end up maintaining lots of fragile mock code which itself doesn't add value to your project.earldouglas
Yeah, I agree having a mock that returns a mock is usually a test smell. For something near the connecting stuff I would instead write integration tests rather than unit tests. About your issue, do you have the same erratic behavior with other classes (like your classes).Brice
Hey guys, thanks for the responses! I definitely agree with you both, that this is far from ideal, and I plan on refactoring the class under test to allow for better dependency injection. I did however solve my problem, and it turns out I made a bone headed mistake. I defined the mock classes using 'def' instead of 'val' or 'var', so it turns out I was creating a new mock every time I called one of the methods. Sorry to waste you guys' time, thanks again for the comments!Bryan

2 Answers

5
votes

Don't accidentally define variables using 'def'! I defined the mocks using 'def' instead of 'val' or 'var', so I created a method that returns a new mock every time, instead of a variable.

0
votes

I think you should define a behavior on connection mock before being able to use it. For example :

when(connection.createChannel()).thenReturn(new Channel {...})

or something like this.