Mocking a Spy method with Mockito

前端 未结 3 1710
时光说笑
时光说笑 2021-02-07 21:54

I am writing a unit test for a FizzConfigurator class that looks like:

public class FizzConfigurator {
    public void doFoo(String msg) {
        d         


        
相关标签:
3条回答
  • 2021-02-07 22:09

    In my case, for the method I was trying to stub, I was passing in incorrect matchers.

    My method signature (for the super class method I was trying to stub): String, Object.

    I was passing in:

    myMethod("string", Mockito.nullable(ClassType.class)) and getting:

    Hints: 1. missing thenReturn() 2. you are trying to stub a final method, which is not supported 3: you are stubbing the behaviour of another mock inside before 'thenReturn' instruction if completed

    When using a matcher in another parameter, we also need to use one for the string:

    myMethod(eq("string"), Mockito.nullable(ClassType.class))

    Hope this helps!

    0 讨论(0)
  • 2021-02-07 22:18

    I wouldn't use exceptions to test that, but verifications. And another problem is that you can't use when() with methods returning void.

    Here's how I would do it:

    FizzConfigurator fixture = Mockito.spy(new FizzConfigurator());
    doNothing().when(fixture).doWidget(Mockito.anyString(), Mockito.<Config>any()));
    fixture.doBuzz("some string");
    Mockito.verify(fixture).doWidget("some string", Config.SOMETIMES);
    
    0 讨论(0)
  • 2021-02-07 22:31

    This is a clear sign that doWidget method should belong to another class which FizzConfigurator would depend on.

    In your test, this new dependency would be a mock, and you could easily verify if its method was called with verify.

    0 讨论(0)
提交回复
热议问题