gpt4 book ai didi

java - 莫基托。未捕获任何参数值

转载 作者:行者123 更新时间:2023-12-01 20:19:26 27 4
gpt4 key购买 nike

应该如何更改此代码以便它不会抛出以下异常?

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());
}
}

验证抛出异常:

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());

最佳答案

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

    @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(..) 参数。

关于java - 莫基托。未捕获任何参数值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45170322/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com