Is there a way to mock construction with mockito-inline only if the constructor arguments match?

3.6k Views Asked by At

I'm having issues getting mockito-inline to handle a case that I would encounter when using PowerMock; mocking a construction, but only when certain arguments are in the construction.

For example

PowerMockito.whenNew(Car.class).withArguments("Red", "Four Wheels", "Expensive").thenReturn(mockedCar);

With mockito-inline, I can mock the construction of a Car by doing

try (MockedConstruction<Car> mockedCar = Mockito.mockConstruction(Car.class)){
    Car c = mockedCar.generated().get(0);

    verify(c).someBehavior();

}

This does not allow me to only generate a mock when I have specific constructor arguments though. Does anybody know how to do this in mockito-inline?

1

There are 1 best solutions below

0
On

You can put Spy instead the Mock if arguments don't match. There's a method that allow to configure mock creating settings:

public static <T> MockedConstruction<T> mockConstruction(
        Class<T> classToMock,
        Function<MockedConstruction.Context, MockSettings> mockSettingsFactory)

So, will be something like that:

mockConstruction(Car::class.java) { context ->
        if (context.arguments() == listOf("Red", "Four Wheels", "Expensive")) {
            withSettings()
        } else {
            withSettings().useConstructor().defaultAnswer(Mockito.CALLS_REAL_METHODS)
        }
    }.use {
        assertEquals(0, Car("Red", "Four Wheels", "Expensive").test()) // mock here
        assertEquals(10, Car("Green", "Four Wheels", "Expensive").test()) // real method called
    }