简体   繁体   中英

How to verify a method was called inside another method with Mockito

I'm fairly new to Mockito, and I've been looking for a way to verify that if I call the filter() method with the right string, that the foo method will get called once.

public class A
{
    private final Config _config;    

    public A(Config config) { _config = config; }

    public void filter(String str)
    {
        if(str.startsWith("a"))
        {
            if(str.contains("z"))
            {
                foo(config.getName());
            }
        }
    }

    private void foo(String bar)
    {
        (...)
    }
}

Here is my current code:

@Test
public void testOne()
{
    Config config = new Config(configFile);
    A a = Mockito.spy(new A(config));
    a.filter("abcz");
    verify(a, times(1)).foo(someString);
}

Try to be more generic while such a test. If you don't need to specify what exactly argument should by passed then just use any() :

import static org.mockito.ArgumentMatchers.any;

verify(a).foo(any(String.class));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM