2017-07-18 32 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

謝謝,適合我。我認爲(例行宣傳)爭論捕獲必須首先初始化。 –

相關問題