测试是否调用了另一种方法

发布于 2021-01-30 16:13:19

因此,我敢肯定那里有类似的东西,但是我一直在寻找一个小时,却没有找到我真正想要的东西。说我有一堂课,看起来像这样:

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

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

我该如何做这样的工作?

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

    // verify myClass.otherMethod method was called
}
关注者
0
被浏览
111
1 个回答
  • 面试哥
    面试哥 2021-01-30
    为面试而生,有面试问题,就找面试哥。

    使用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();
        }
    }
    

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



知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看