Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading