Mockito在调用getter时不使用构造函数中的值?

huangapple go评论57阅读模式
英文:

Mockito not using value in constructor when getter called?

问题

我有以下的Pojo:

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

    public Double getPrice() {
        return price;
    }
}

我认为当我在单元测试中创建我的模拟对象时,如下所示:

@Mock
Football football;

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

当我在我的足球模拟对象上调用getPrice()方法时,应该返回18.99,因为价格是硬编码在构造函数参数中。然而实际情况并非如此。

为什么会出现这种情况?

英文:

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?

答案1

得分: 1

这正是预期发生的情况。

一个模拟对象是一个对象,其中所有的方法(除了一些有文档记录的例外)要么已被替换为不执行任何操作并根据方法的返回类型返回null、零、false或空,要么已被您自己指定行为和返回值,通过对方法进行存根处理。

这包括你示例中的getPrice方法。它已被替换为一个什么都不做并返回0.0的方法。

在Mockito中,返回类型为原始类型,如doubleint等,以及包装类型,如DoubleInteger等的方法,如果您没有对它们进行存根处理,将返回相应类型的零或false。

英文:

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.

huangapple
  • 本文由 发表于 2023年2月10日 07:14:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/75405435.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定