Search code examples
javatestingassert

Why does this java test read false instead of true?


In java I have a test here are few lines of code from it:

StrategySlide strategySlide = mock(StrategySlide.class);
assertTrue(strategySlide.canSlide(board, fromCoords, toCoords));

This is a part of the canSlide code (i just put return true at the top to make sure it would always return true):

abstract public class StrategySlide implements StrategyFactoryI {

    public boolean canSlide(Board board, Coordinates from, Coordinates to) {
        return true;
    }
}

However upon running only this test I get the following output:

expected: <true> but was: <false>
Expected :true
Actual   :false

I have no idea why it would read false when I just do return true. Does anyone have a idea how this could happen?


Solution

  • That's because you're mocking strategySlide and Mockito by default returns false for mocked methods that return a boolean.

    From the documentation:

    By default, for all methods that return a value, a mock will return either null, a primitive/primitive wrapper value, or an empty collection, as appropriate. For example 0 for an int/Integer and false for a boolean/Boolean.

    If you want to test the actual implementation, then you shouldn't mock StrategySlide but create a new instance through the normal ways (eg. new StrategySlide()).

    If you want to use Mockito to return a different value, you can use:

    when(strategySlide.canSlide(any(), any(), any()).thenReturn(true);
    

    (when() comes from Mockito.when() and any() comes from ArgumentMatchers.any())