Mock() as a parameter

Hello,

I ran into an usage in tdd books but I could not understand.

factory.buildGame(mock())

we are passing mock(). what does it mean exactly?

Thanks in advance.

Hi @abdullahsen thanks for your question!

As explained in Chapter 7, mock() is a function from Mockito to instantiate a mock. It’ll instantiate a mock of the type you specify. E.g. mock<Callback>() would return a Callback type. If you don’t specify the type, the compiler will try to infer it.

Usually, in a test, after instantiating a mock, you can use it to stub methods and/or verify if methods of the mock were called.

However, sometimes, you just need to call a method that requires a parameter of a specific type. Instead of passing a real parameter you can just pass a mock object.

In this case, checking the source code here, you can see the following:

fun buildGame(callback: Callback)

This means the method expects a Callback parameter.

In the test, if you don’t care to pass an actual Callback you can just pass a mock, therefore you can do:

factory.buildGame(mock())

Hope it clarifies.

Thanks!