Java Mockito定义';何时';援引答案

Java Mockito定义';何时';援引答案,java,unit-testing,junit,mockito,Java,Unit Testing,Junit,Mockito,我需要模拟一个JDBCUPDATE语句,并确保发送的update字符串是正确的。我有一个MockConnectionManager,它定义了以下方法来定义预期的查询字符串: public void setUpdateExpectedQuery(String ...expectedQueryStrings) throws SQLException { Statement mockStatement = mock(Statement.class); when(mockConnect

我需要模拟一个JDBCUPDATE语句,并确保发送的update字符串是正确的。我有一个MockConnectionManager,它定义了以下方法来定义预期的查询字符串:

public void setUpdateExpectedQuery(String ...expectedQueryStrings) throws SQLException {

    Statement mockStatement = mock(Statement.class);
    when(mockConnection.createStatement()).thenReturn(mockStatement);

    when(mockStatement.executeUpdate(anyString())).then(new Answer<String>() {

        @Override
        public String answer(InvocationOnMock invocationOnMock) throws Throwable {
            String str = Arrays.toString(invocationOnMock.getArguments());
            throw new RuntimeException("Update string is not as expected: " + str);
        }

    });

    for(String expected : expectedQueryStrings) {
        when(mockStatement.executeUpdate(expected)).then(new Answer<Void>() {

            @Override
            public Void answer(InvocationOnMock invocationOnMock) throws Throwable {
                // Do something, just don't throw an exception here.
                return null;
            }

        });
    }
}
与第一个答案中所写的异常相同:java.lang.RuntimeException:Update字符串与预期不符:[在任何时候插入任何内容]


这怎么可能?调用“when”是否实际调用了该方法?我从未在其他情况下看到过这种情况…

我怀疑问题在于循环中的调用(当调用
mockStatement.executeUpdate(预期)
时)与之前对
的模拟(mockStatement.executeUpdate(anyString())
相匹配

记住,mock知道您在
when
中调用什么的方式是因为您正在调用它-想象一下将
when(mockStatement.executeUpdate(anyString())
转换为:

int result = mockStatement.executeUpdate(anyString());
OngoingStubbing<Integer> tmp = when(result);
tmp.then(...);

引发了什么异常?第一个答案中的一个:java.lang.RuntimeException:Update string不像预期的那样:[在where中插入WHATEVER]当您这样放置它时,它是有意义的:)这意味着如果其中一个具有anyString()之类的匹配器,我就不能真正使用多个'When'子句……@apines:可能有一种方法可以做到这一点,但我不知道那是什么。
int result = mockStatement.executeUpdate(anyString());
OngoingStubbing<Integer> tmp = when(result);
tmp.then(...);
public void setUpdateExpectedQuery(String ...expectedQueryStrings)
    throws SQLException {
    final Set<String> capturedQueries = new HashSet<>
       (Arrays.asList(expectedQueryStrings);

    Statement mockStatement = mock(Statement.class);
    when(mockConnection.createStatement()).thenReturn(mockStatement);

    when(mockStatement.executeUpdate(anyString())).then(new Answer<String>() {    
        @Override
        public String answer(InvocationOnMock invocationOnMock) throws Throwable {
            String query = (String) invocationOnMock.getArguments[0];
            if (capturedQueries.contains(query)) {
                return null;
            }
            throw new RuntimeException("Update string is not as expected: " + query);
        }

    });
}