Mockito, considering stubbing as a challenge

Trying to stub a class in two possible ways to call / return using a custom Matcher ... ran into a problem of interest.

Here is a test I wrote to illustrate ...

It may be difficult to implement, but I expected that the first ArgumentMatcherwould not be called when the second was executedwhen(...).thenReturn(...)

But by running the code below, type foobaron stdout. Is there something we can do to prevent this behavior? Or am I using the wrong template trying to drown out a single layout with multiple customArgumentMatcher

FYI - powermockis in my classpath for other tests (not sure if this is important, but I see it in the stack trace)

import org.junit.Test;
import org.mockito.ArgumentMatcher;

import java.io.File;
import java.io.FilenameFilter;

import static org.mockito.Matchers.*;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

public class MyTest {
    @Test
    public void name() throws Exception {
        File file = mock(File.class);
        when(file.list(argThat(new ArgumentMatcher<FilenameFilter>() {
            @Override
            public boolean matches(Object argument) {
                System.out.println("foobar");
                return 1 + 1 >2;
            }
        }))).thenReturn(null);
        // at this point, mockito will attempt to run the previous matcher, treating this stub code as invocation ... and printing out 'foobar'
        when(file.list(argThat(new ArgumentMatcher<FilenameFilter>() {
            @Override
            public boolean matches(Object argument) {
                System.out.println("barbar");
                return true;
            }
        }))).thenReturn(null);

    }
}

EDIT ,

+4
1

doReturn(), .

doReturn(null).when(file).list(argThat(new ArgumentMatcher<FilenameFilter>() {
    @Override
    public boolean matches(Object argument) {
        System.out.println("barbar");
        return true;
    }
}));

. . , ( ):

doReturn(), [...] if() . , :

  • stub void
  • - - (. )
  • , .
+4

Source: https://habr.com/ru/post/1662676/


All Articles