Mockito的doAnswer和answer

  在单元测试中,有assert来判断测试的结果,verfiy来判断执行的次数和顺序,doAnswer用来判断执行的方法和方法的参数。
    doAnswer一般和when配合使用,当条件满足是,执行对应的Answer的answer方法,如果answer方法抛出异常,那么测试不通过。
    这是我的一个实例:





import java.util.List;

import org.junit.Test;
import org.mockito.Mockito;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
 import static org.mockito.Mockito.*;

public class CustomAnswer implements Answer<String> {
    public String answer(InvocationOnMock invocation) throws Throwable {
        Object[] args = invocation.getArguments();
        Integer num = (Integer)args[0];
        if( num>3 ){
            return "yes";
        } else {
            throw new RuntimeException();
        }
    }
    
    
    @Test
    public void customAnswerTest(){
        List<String> mock = mock(List.class);
        Mockito.doAnswer(new CustomAnswer()).when(mock).get(anyInt());
        mock.get(4); 
        mock.get(2); 
        
    }

    
}


当 mock.get(2); 的时候,执行判断,这个时候num>3 不成立,抛出异常,测试不通过。

answer方法中通过参数invocation能获取的东西是这些:一般判断方法的参数

public interface InvocationOnMock extends Serializable {

    /**
     * returns the mock object 
     * 
     * @return mock object
     */
    Object getMock();

    /**
     * returns the method
     * 
     * @return method
     */
    Method getMethod();

    /**
     * returns arguments passed to the method
     * 
     * @return arguments
     */
    Object[] getArguments();

    /**
     * calls real method
     * <p>
     * <b>Warning:</b> depending on the real implementation it might throw exceptions  
     *
     * @return whatever the real method returns / throws
     * @throws Throwable in case real method throws 
     */
    Object callRealMethod() throws Throwable;
}

猜你喜欢

转载自huangyunbin.iteye.com/blog/1883501
今日推荐