简体   繁体   English

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

[英]How to verify if method was called from other with same class by mockito

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;
    }
}

So I want to test if the method getPriceForOne() was called when calling the method getPrice(int).所以我想测试在调用方法getPrice(int)时是否调用了方法getPriceForOne()。 Basically call getPrice(int) as normal and mock getPriceForOne.基本上正常调用 getPrice(int) 并模拟 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.请记住,我有一个更复杂的文件,它是供其他人使用的实用程序,它们必须都在一个文件中。

You would need a spy, not a mock A:你需要一个间谍,而不是一个模拟 A:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何验证mockito是否从其他方法调用了方法 - How to verify if method was called from other by mockito 如何验证未使用 Mockito 调用特定方法? - How to verify that a specific method was not called using Mockito? 如何验证Mockito是否满足许多条件? 是否可以验证是否调用了一个或另一个方法? - How to verify one from many conditions is satisfied on Mockito? Is it possible to verify if one OR another method was called? Mockito:如何验证一个方法只被调用一次,而忽略对其他方法的调用的精确参数? - Mockito: How to verify a method was called only once with exact parameters ignoring calls to other methods? Mockito验证方法一次调用 - Mockito verify method called once 如何验证使用 mockito 调用公共类的 static 方法? - How to verify a public class's static method get called using mockito? 如何使用 Mockito 验证在另一个方法中调用了一个方法 - How to verify a method was called inside another method with Mockito Mockito:如何验证在方法中创建的 object 上调用了方法? - Mockito : how to verify method was called on an object created within a method? 如何使用Mockito验证一个方法是否在另一个方法中被调用? - How to use Mockito to verify a method is called in another method? Mockito 正在调用主类的方法 - Method from main class is getting called for Mockito
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM