/*
  * Copyright (c) 2007 Mockito contributors
  * This program is made available under the terms of the MIT License.
  */
  package org.mockitousage.stubbing;
   
  import org.junit.Test;
  import org.mockito.Mock;
  import org.mockito.invocation.InvocationOnMock;
  import org.mockito.stubbing.Answer;
  import org.mockitousage.IMethods;
  import org.mockitoutil.TestBase;
   
  import java.lang.reflect.Method;
  import java.util.Set;
   
  import static org.junit.Assert.*;
  import static org.mockito.Mockito.*;
   
  public class StubbingWithCustomAnswerTest extends TestBase {
  @Mock
  private IMethods mock;
   
  @Test
  public void shouldAnswer() throws Exception {
  when(mock.simpleMethod(anyString())).thenAnswer(new Answer<String>() {
  public String answer(InvocationOnMock invocation) throws Throwable {
  String arg = invocation.getArgument(0);
   
  return invocation.getMethod().getName() + "-" + arg;
  }
  });
   
  assertEquals("simpleMethod-test", mock.simpleMethod("test"));
  }
   
  @Test
  public void shouldAnswerWithThenAnswerAlias() throws Exception {
  RecordCall recordCall = new RecordCall();
  Set<?> mockedSet = (Set<?>) when(mock(Set.class).isEmpty()).then(recordCall).getMock();
   
  mockedSet.isEmpty();
   
  assertTrue(recordCall.isCalled());
  }
   
  @Test
  public void shouldAnswerConsecutively() throws Exception {
  when(mock.simpleMethod())
  .thenAnswer(new Answer<String>() {
  public String answer(InvocationOnMock invocation) throws Throwable {
  return invocation.getMethod().getName();
  }
  })
  .thenReturn("Hello")
  .thenAnswer(new Answer<String>() {
  public String answer(InvocationOnMock invocation) throws Throwable {
  return invocation.getMethod().getName() + "-1";
  }
  });
   
  assertEquals("simpleMethod", mock.simpleMethod());
  assertEquals("Hello", mock.simpleMethod());
  assertEquals("simpleMethod-1", mock.simpleMethod());
  assertEquals("simpleMethod-1", mock.simpleMethod());
  }
   
  @Test
  public void shouldAnswerVoidMethod() throws Exception {
  RecordCall recordCall = new RecordCall();
   
  doAnswer(recordCall).when(mock).voidMethod();
   
  mock.voidMethod();
  assertTrue(recordCall.isCalled());
  }
   
  @Test
  public void shouldAnswerVoidMethodConsecutively() throws Exception {
  RecordCall call1 = new RecordCall();
  RecordCall call2 = new RecordCall();
   
  doAnswer(call1)
  .doThrow(new UnsupportedOperationException())
  .doAnswer(call2)
  .when(mock).voidMethod();
   
  mock.voidMethod();
  assertTrue(call1.isCalled());
  assertFalse(call2.isCalled());
   
  try {
  mock.voidMethod();
  fail();
  } catch (UnsupportedOperationException e) {
  }
   
  mock.voidMethod();
  assertTrue(call2.isCalled());
  }
   
  @Test
  public void shouldMakeSureTheInterfaceDoesNotChange() throws Exception {
  when(mock.simpleMethod(anyString())).thenAnswer(new Answer<String>() {
  public String answer(InvocationOnMock invocation) throws Throwable {
  assertTrue(invocation.getArguments().getClass().isArray());
  assertEquals(Method.class, invocation.getMethod().getClass());
   
  return "assertions passed";
  }
  });
   
  assertEquals("assertions passed", mock.simpleMethod("test"));
  }
   
  private static class RecordCall implements Answer<Object> {
  private boolean called = false;
   
  public boolean isCalled() {
  return called;
  }
   
  public Object answer(InvocationOnMock invocation) throws Throwable {
  called = true;
  return null;
  }
  }
   
  }

2.    当mock一个对象,且执行此对象中的方法没有返回值时,使用下面的方法:

import org.mockito.Mockito;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;

类名   对象 = Mockito.mock(类名.class);
        Mockito.doAnswer(new Answer<Object>() {
            public Object answer(InvocationOnMock invocation) {
                Object[] args = invocation.getArguments();
                return "called with arguments: " + args;
            }
        }).when(对象).方法名();

---------------------

本文来自 flysun3344 的CSDN 博客 ,全文地址请点击:https://blog.csdn.net/flysun3344/article/details/52065492?utm_source=copy

mock获取入参数并动态设置返回值的更多相关文章

  1. 常量函数、常量引用参数、常量引用返回值[C++]

    1. 关于常量引用正像在C语言中使用指针一样,C++中通常使用引用 有一个函数... foo()并且这个函数返回一个引用...... & foo()...., 一个指向位图(Bitmap)的引 ...

  2. 使用 ResponseBodyAdvice 拦截Controller方法默认返回参数,统一处理返回值/响应体

    使用 @ControllerAdvice & ResponseBodyAdvice 拦截Controller方法默认返回参数,统一处理返回值/响应体 1.Controller代码 以下是Con ...

  3. day03 函数基本语法及特性 2. 参数与局部变量 3. 返回值 嵌套函数 4.递归 5.匿名函数 6.函数式编程介绍 7.高阶函数 8.内置函数

    本节内容 1. 函数基本语法及特性 2. 参数与局部变量 3. 返回值 嵌套函数 4.递归 5.匿名函数 6.函数式编程介绍 7.高阶函数 8.内置函数 温故知新 1. 集合 主要作用: 去重 关系测 ...

  4. Java程序调用带参数的shell脚本返回值

    Java程序调用带参数的shell脚本返回值 首先来看看linux中shell变量(\(#,\)@,$0,$1,\(2)的含义解释 变量说明: -  \)$  Shell本身的PID(ProcessI ...

  5. JQuery/JS select标签动态设置选中值、设置禁止选择 button按钮禁止点击 select获取选中值

    //**1.设置选中值:(根据索引确定选中值)**// var osel=document.getElementById("selID"); //得到select的ID var o ...

  6. c++11之获取模板函数的参数个数和函数返回值类型

    本文演示c++需要支持c++11及以上标准 获取参数个数 1.模板函数声明 template <class R, class... Args> R getRetValue(R(*)(Arg ...

  7. c语言main函数返回值、参数详解(返回值是必须的,0表示正常退出)

    C语言Main函数返回值 main函数的返回值,用于说明程序的退出状态.如果返回0,则代表程序正常退出:返回其它数字的含义则由系统决定.通常,返回非零代表程序异常退出. 很多人甚至市面上的一些书籍,都 ...

  8. c++特性:指向类成员的指针和非类型类模板参数和函数指针返回值 参数推导机制和关联型别

    一.c++允许定义指向类成员的指针,包括类函数成员指针和类数据成员指针 格式如下: class A { public: void func(){printf("This is a funct ...

  9. [android] setOnTouchEvent 设置返回值为true 和 false的区别

    今天在做自定义的可选文本的 TextView 类时,用到了 View 类的 setOnTouchListener(OnTouchListener l)事件监听,在构造 OnTouchListener ...

随机推荐

  1. 【linux】centos6.9安装gearman

    1.确认yum源没问题,如果有问题,参照这里更换 2. yum install -y boost-devel gperf libevent-devel libuuid-devel yum instal ...

  2. iOS学习笔记之触摸事件&UIResponder

    iOS学习笔记之触摸事件&UIResponder 触摸事件 与触摸事件相关的四个方法如下: 一根手指或多根手指触摸屏幕 -(void)touchesBegan:(NSSet *)touches ...

  3. 学习Struts2经验总结

    一.struts 访问路径问题 1) Struts2的思想:主要围着“action”转,只要找到“action”它就知道自己该干嘛了. 首先配置struts.xml ,我们可以明白的看到,action ...

  4. 微信h5支付源码DEMO参考

    类库代码 wechatH5Pay.php <?php //use Flight; /** * 微信支付服务器端下单 * 微信APP支付文档地址: https://pay.weixin.qq.co ...

  5. HDU 1075 字符串映射(map)

    Sample InputSTARTfrom fiwohello difhmars riwosfearth fnnvklike fiiwjENDSTARTdifh, i'm fiwo riwosf.i ...

  6. 开始写博客,学习Linq(2)

    linq的功能是什么? 它将极大地改变应用程序或组件处理数据的方式.这是第一个功能. LINQ to Objects.LINQ to SQL和LINQ to XML,是LINQ三大主要功能,当然LIN ...

  7. day8--socketserver

    socketserver分类: 1.TCP协议 class socketserver.TCPServer(server_address,RequestHandlerClass,bind_and_act ...

  8. URAL - 1427-SMS

    题目大意:给你长度为n的字符串(n<=1e6),让你对它进行划分,如果一段里面只有字母和 空格可以包含m(m<=1e5)个,如果有其他字符只能包含n个,问你最少需要分成几段. 思路:划分d ...

  9. drupal的node.html.twig说明

    Drupal 8 根据分类不同定义自己的节点模板建议:http://www.thinkindrupal.com/node/5986 *可用变量: * - node:具有有限访问对象属性和方法的节点实体 ...

  10. RelativeLayout的16种特有属性

    *相对于兄弟控件的位置属性 android:layout_above="@id/center_btn"处于某一个控件的上方 android:layout_below="@ ...