当方法将字符串数组作为参数时的嘲弄,并且参数有一些值Java

Mockery when method takes string array as argument, and argument has some values Java

我必须编写一个测试用例,我必须为此模拟一个具有以下签名的方法:

public X testMethod(String[] args);

现在我要模拟的场景是:

when(xyz.testMethod(
                       // args contains "AAA" and "BBB"
                   ).thenReturn(x1);

when(xyz.testMethod(
                       // args contains "CCC" and "DDD"
                   ).thenReturn(x2);

没有得到指针,我该如何模拟这种情况

您可以使用 .thenAnswer() 进行动态响应 类似于:

    Mockito.when(xyz.testMethod(Mockito.anyObject())).thenAnswer(e -> {
        String[] args = (String[]) e.getArguments()[0];
        // do your contains logic here
        return x1; // or x2
    })

诀窍是使用org.mockito.ArgumentMatchers.argThat

它不适用于 when...thenReturn。您必须使用 doReturn...when 而不是

public class X {
    //
}

public interface XYZ {
    X testMethod(String[] args);
}

使用 Mockito2、JUnit4 和 Java8 这些测试是绿色的:

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;

import java.util.Arrays;

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

public class MyTest {
    private XYZ xyz;
    private X x1;
    private X x2;

    @Before
    public void setUp() {
        xyz = mock(XYZ.class);
        x1 = new X();
        x2 = new X();
        doReturn(x1).when(xyz).testMethod(argThat(contains("AAA", "BBB")));
        doReturn(x2).when(xyz).testMethod(argThat(contains("CCC", "DDD")));
    }

    private static ArgumentMatcher<String[]> contains(String... args) {
        return array -> Arrays.asList(array).containsAll(Arrays.asList(args));
    }

    @Test
    public void testMethod_whenArgsContainsAAA_and_BBB_shouldReturn_x1() {
        X actual = xyz.testMethod(new String[] {"AAA", "BBB"});

        assertEquals(x1, actual);
    }

    @Test
    public void testMethod_whenArgsContainsCCC_and_DDD_shouldReturn_x2() {
        X actual = xyz.testMethod(new String[] {"CCC", "DDD"});

        assertEquals(x2, actual);
    }

    @Test
    public void neitherNor() {
        X actual = xyz.testMethod(new String[] {"EEE", "FFF"});

        assertNull(actual);
    }
}