Mockito 学习篇(四)完结

Mockito学习篇目录:

Mockito 学习篇(一)

Mockito 学习篇(二)

Mockito 学习篇(三)

Mockito 学习篇(四)完结

package org.zheng.mockito;

/**
 * Create by zxb on 2017/9/2
 */
public class ConstructorTest{

    public ConstructorTest() {
        System.out.println("Here's in constructor");
    }
}

package org.zheng.mockito;

import lombok.Data;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.runners.MockitoJUnitRunner;

import java.util.LinkedList;

import static org.mockito.Mockito.*;

/**
 * MockitoTester.
 *
 * @author zxb
 * @version 1.0
 * @since <pre>09/02/2017</pre>
 */
@RunWith(MockitoJUnitRunner.class)
public class MockitoTest4 {

    @Data
    class SandBox {

        private Sand sand;
    }

    interface Sand {

        Integer doA();
    }

    @Test
    public void test() throws InterruptedException {
        //mock对象时,修改默认返回值策略
        LinkedList mockList = mock(LinkedList.class
                , withSettings().defaultAnswer(RETURNS_SMART_NULLS));
        Assert.assertNotNull(mockList.get(0));

        //mock对象时,使用默认调用真实方法
        LinkedList mockList2 = mock(LinkedList.class
                , withSettings().defaultAnswer(CALLS_REAL_METHODS));
        mockList2.add(1);
        Assert.assertTrue(1 == mockList2.size());

        //mock对象时,使用默认构造函数(或者自己实现的)
        ConstructorTest constructorTest = mock(ConstructorTest.class
                , withSettings().useConstructor().defaultAnswer(RETURNS_SMART_NULLS));  //打印:Here's in constructor
        ConstructorTest constructorTest2 = mock(ConstructorTest.class);  // 不会打印
        Assert.assertNotNull(constructorTest);

        //Deep Stubs 可进行调用链上的mock,mock理解为树模型
        SandBox sandBox = mock(SandBox.class, RETURNS_DEEP_STUBS);
        SandBox sandBox2 = mock(SandBox.class);
        System.out.println("doA()=" + sandBox.getSand().doA());  //打印:doA()=0
        try {
            sandBox2.getSand().doA();
        } catch (Exception ex) {
            System.out.println("Exception!因为调用链上getSand已为null");
        }
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值