2017-07-18 136 views
0

应如何更改此代码以便它不会抛出异常?Mockito。没有捕获任何参数值

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

如果你只是证实发生了零次事件,你怎么能期望已经捕获它的论点? – khelwood

+0

解决方法为零时,应该将其删除,但如果删除它将引发另一个异常。有些东西是错误的,但我不知道什么以及如何正确使用它 –

+0

但该方法尚未被调用。这就是'verify(...,times(0))'正在验证的内容。所以没有任何俘获的理由让你得到。 – khelwood

回答

3

您应该调用类的方法测试第一。然后,您验证使用的俘虏:

@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(..)说法。

+0

谢谢,适合我。我认为(例行宣传)争论捕获必须首先初始化。 –