Search code examples
javaunit-testingjunitmockitojunit-jupiter

Mockito not using value in constructor when getter called?


I have the following Pojo:

public class Football extends Item {
    public Football(Colour colour, Double price ) {
        super(colour, 18.99);
    }

    public Double getPrice() {
        return price;
    }

}

I thought that when I created my mock in unit test as such:

@Mock
Football football;

@BeforeEach
private void initMocks() {
    MockitoAnnotations.openMocks(this);
}

When I call the method getPrice() on my football mock - I should get 18.99 back as the price is hardcoded in the constructor params. However I do not.

Why is this the case?


Solution

  • This is precisely what's supposed to happen.

    A mock is an object where all the methods (with some documented exceptions) have been replaced EITHER

    • by a method that does nothing, and returns either null, zero, false or empty, depending on the method's return type; OR
    • by a method whose behaviour and return value you've specified yourself, via stubbing the method.

    This includes the getPrice method in your example. It's been replaced by a method that does nothing and returns 0.0.

    In Mockito, methods whose return types are

    • primitive types, like double, int and so on,
    • wrapper types, like Double, Integer and so on,

    will return the appropriate kind of zero/false, if you haven't stubbed them to do otherwise.