如何验证方法是否通过mockito从具有相同类的其他方法调用 [英] How to verify if method was called from other with same class by mockito

查看:100
本文介绍了如何验证方法是否通过mockito从具有相同类的其他方法调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想测试一些在同一个类中调用其他人的方法。它基本上是相同的方法,但参数较少,因为数据库中有一些默认值。我在此显示

I want test some methods thats call others in the same class. It is basically same methods, but with less arguments because there is some default values in a database. I show on this

public class A{
    Integer quantity;
    Integer price;        

    A(Integer q, Integer v){
        this quantity = q;
        this.price = p;
    }

    public Float getPriceForOne(){
        return price/quantity;
    }

    public Float getPrice(int quantity){
        return getPriceForOne()*quantity;
    }
}

所以我想测试是否被调用方法getPriceForOne()当调用方法getPrice(int)时。基本上调用普通方法getPrice(int)和mock getPriceForOne。

So i want test if was called method getPriceForOne() when calling method getPrice(int). Basically call normal method getPrice(int) and mock getPriceForOne.

import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
....

public class MyTests {
    A mockedA = createMockA();

    @Test
    public void getPriceTest(){
        A a = new A(3,15);
        ... test logic of method without mock ...

        mockedA.getPrice(2);
        verify(mockedA, times(1)).getPriceForOne();
    }
}

考虑我有更复杂的文件,这是一个实用工具其他人必须全部在一个文件中。

Consider I have much more complicated file thats a utility for others and must be all in one file.

推荐答案

你需要一个间谍,而不是模拟A:

You would need a spy, not a mock A:

    A a = Mockito.spy(new A(1,1));
    a.getPrice(2);
    verify(a, times(1)).getPriceForOne();

这篇关于如何验证方法是否通过mockito从具有相同类的其他方法调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆