测试是否调用了另一种方法 [英] Test if another method was called

查看:70
本文介绍了测试是否调用了另一种方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我敢肯定那里有类似的东西,但是我已经搜索了一个小时,还没有找到我想要的东西.说我有一堂课,像这样:

So I'm sure there is something like this out there but I have been searching for an hour and haven't found exactly what I am looking for. say I have a class that looks like this:

public class MyClass
{
    public void myMethod(boolean shouldCallOtherMethod)
    {
        if(shouldCallOtherMethod)
        {
            otherMethod();
        }
    }

    public void otherMethod()
    {
        System.out.println("Called");
    }
}

我该如何做类似的事情?

How do I make something like this work?

@Test
public void shouldCallMethod()
{
    MyClass myClass = new MyClass();
    myClass.myMethod(true)

    // verify myClass.otherMethod method was called
}

推荐答案

使用 Mockito ,您可以像这样监视真实对象:

import org.junit.Test;
import static org.mockito.Mockito.*;
public class MyClassTest {
    @Test
    public void otherMethodShouldBeCalled() {
        MyClass myClass = new MyClass();
        MyClass spy = spy(myClass);

        spy.myMethod(true);
        verify(spy).otherMethod();
    }
}

有一些陷阱,因此请查看相关文档.

There are some gotchas, so take a look at the relevant documentation as well.

这篇关于测试是否调用了另一种方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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