Mockito,未捕获任何参数值

nhaq1z21  于 2022-11-08  发布在  其他
关注(0)|答案(2)|浏览(131)

如何更改此代码,使其不会引发以下异常?

ArgumentCaptor<Date> argument = forClass(Date.class);
verify(ps, times(0)).setDate(anyInt(), argument.capture());

typeHandler.setNonNullParameter(ps, 1, "20170120", DATE);

assertEquals(new Date(2017, 01, 20), argument.getValue());

更多代码:

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.joda.time.LocalDate;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;

import java.sql.*;

public class DateStringTypeHandler extends BaseTypeHandler<String> {

    private static final DateTimeFormatter YYYY_MM_DD = DateTimeFormat.forPattern("yyyyMMdd");

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, String parameter, JdbcType jdbcType) throws SQLException {
        LocalDate localDate = YYYY_MM_DD.parseLocalDate(parameter);
        ps.setDate(i, new Date(localDate.toDateTimeAtStartOfDay().getMillis()));
    }
}

@RunWith(MockitoJUnitRunner.class)
public class DateStringTypeHandlerTest {

    @Mock
    private PreparedStatement ps;
    private DateStringTypeHandler typeHandler;

    @Before
    public void before() {
        typeHandler = new DateStringTypeHandler();
    }

    @Test
    public void testSetNonNullParameterPreparedStatementIntStringJdbcType() throws SQLException {
        ArgumentCaptor<Date> argument = forClass(Date.class);
        verify(ps, times(0)).setDate(anyInt(), argument.capture());

        typeHandler.setNonNullParameter(ps, 1, "20170120", DATE);

        assertEquals(new Date(2017, 01, 20), argument.getValue());
    }
}

verify抛出异常:

org.mockito.exceptions.base.MockitoException: 
No argument value was captured!
You might have forgotten to use argument.capture() in verify()...
...or you used capture() in stubbing but stubbed method was not called.
Be aware that it is recommended to use capture() only with verify()

Examples of correct argument capturing:
    ArgumentCaptor<Person> argument = ArgumentCaptor.forClass(Person.class);
    verify(mock).doSomething(argument.capture());
    assertEquals("John", argument.getValue().getName());
wvt8vs2t

wvt8vs2t1#

首先应该调用被测类的方法,然后使用捕获器进行验证:

@Test
    public void testSetNonNullParameterPreparedStatementIntStringJdbcType() throws SQLException {
        // Arrange
        ArgumentCaptor<Date> argument = forClass(Date.class);

        // Act
        typeHandler.setNonNullParameter(ps, 1, "20170120", DATE);

        // Assert            
        verify(ps).setDate(anyInt(), argument.capture());    
        assertEquals(new Date(2017, 01, 20), argument.getValue());
    }

同样,现在您可能不需要times(..)参数。

3z6pesqy

3z6pesqy2#

我也遇到了同样的问题。当我调试它的时候,问题变成了当调试器离开函数的时候,函数内部声明的捕获器的局部作用域减小了,所以我得到了错误。
尝试在函数外部的类内部创建/声明捕获器变量。它起作用了!

相关问题