如何通过mockito验证是否从其他具有相同类的方法调用

How to verify if method was called from other with same class by mockito(如何通过mockito验证是否从其他具有相同类的方法调用)
本文介绍了如何通过mockito验证是否从其他具有相同类的方法调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我想测试一些在同一个类中调用其他方法的方法.它们基本上是相同的方法,但具有不同数量的参数,因为数据库中有一些默认值.我在这个上显示

I want to test some methods that call others in the same class. They are basically the same methods, but with different numbers of arguments because there are 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;
    }
}

所以我想测试调用getPrice(int)方法时是否调用了getPriceForOne()方法.基本上像平常一样调用 getPrice(int) 并模拟 getPriceForOne.

So I want to test if the method getPriceForOne() was called when calling the method getPrice(int). Basically call getPrice(int) as normal 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();
    }
}

请记住,我有一个更复杂的文件,它是其他人的实用程序,它们必须都在一个文件中.

Please keep in mind that I have a much more complicated file that's a utility for others and they must all be 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验证是否从其他具有相同类的方法调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

Sending a keyboard event from java to any application (on-screen-keyboard)(将键盘事件从 java 发送到任何应用程序(屏幕键盘))
How to make JComboBox selected item not changed when scrolling through its popuplist using keyboard(使用键盘滚动其弹出列表时如何使 JComboBox 所选项目不更改)
Capturing keystrokes without focus(在没有焦点的情况下捕获击键)
How can I position a layout right above the android on-screen keyboard?(如何将布局放置在 android 屏幕键盘的正上方?)
How to check for key being held down on startup in Java(如何检查在Java中启动时按住的键)
Android - Get keyboard key press(Android - 获取键盘按键)