单元测试——各种方法行为怎么mock

mock被测试方法中多次调用的方法行为

情景描述:
在被测试方法中多处调用Utils工具类的checkCollection方法,并且每次返回的结果不同;

解决方法:
when后面跟上多个thenReturn表示第几次调用返回结果;

PowerMockito.when(Utils.checkCollection(companyList))
                .thenReturn(true).thenReturn(true).thenReturn(true);

mock静态方法行为

PowerMockito.mockStatic(Utils.class);

mock无返回值的方法

 doNothing().when(dao).updateDeptBatch(list);
 //            对象          方法名       参数

mock集合的方法行为

        List list = Mockito.mock(ArrayList.class);
        PowerMockito.whenNew(ArrayList.class).withNoArguments().thenReturn((ArrayList) list);
  PowerMockito.when(list.size()).thenReturn(mocklist的size);

被mock的方法中需要传入真实参数时

// 声明
private ArrayList<EsPersonInfo> arrayList;

//创建真实对象
 @Before
    public void setUp() throws Exception {
        MockitoAnnotations.initMocks(this);
        dialerService= new DialerServiceImpl(dao, cache, groupInfoModifyPushService);
        arrayList=new ArrayList<>();
    }
//传入方法
this.dialerService.updatePerson(arrayList,1L, arrayList);

@mock和@spy mock私有方法时的区别

@mock会创造出虚拟的方法行为而@spy会执行真正的方法代码;

如果被测试类中调用了自己的私有方法,mock私有方法的行为

假设私有方法执行成功,直接跳过

 dialerService = PowerMockito.spy(dialerService);
 PowerMockito.doNothing().when(dialerService, "distinguishPersonsUpdateAndInsert", anySet(), anyList(), anyList(), anyList());

不跳过

Method method = PowerMockito.method(EcssDataSyncService.class, "extractCompanyGroup",class);
            method.invoke(ecssDataSyncService,args);

mock私有方法行为时,私有方法抛出异常如何捕获

 try {
            Method method = PowerMockito.method(EcssDataSyncService.class, "extractCompanyGroup");
            method.invoke(ecssDataSyncService);
        }catch (Exception s){
            InvocationTargetException exception=(InvocationTargetException)s;
            Throwable t = exception.getTargetException();
            assertEquals(t.getMessage(),"Failed to sync company.");
        }

如何Mock从配置文件中注入的属性

    @Value("${" + ConfigKeys.PERIOD_ACCESS_TOKEN_DEFAULT + "}")
    private String accessTokenPeriod;
    @Value("${" + ConfigKeys.PERIOD_REFRESH_TOKEN_DEFAULT + "}")
    private String refreshTokenPeriod;

通过spring提供了反射工具类:

        ReflectionTestUtils.setField(tokenService,"accessTokenPeriod",accessTokenPeriod);
        ReflectionTestUtils.setField(tokenService,"refreshTokenPeriod",refreshTokenPeriod);

如何mock httpClientc

测试执行到httpClient

PowerMockito.when(HttpClientUtils.post(anyString(),anyMap(),anyString(),
                anyString(),anyString(),any(),any())).thenReturn(null);

出现报错

Caused by: org.apache.http.ssl.SSLInitializationException: class configured for SSLContext: sun.security.ssl.SSLContextImpl$TLSContext not a SSLContext
	at org.apache.http.ssl.SSLContexts.createDefault(SSLContexts.java:55)
	at org.apache.http.conn.ssl.SSLConnectionSocketFactory.getSocketFactory(SSLConnectionSocketFactory.java:174)
	at org.apache.http.impl.conn.PoolingHttpClientConnectionManager.getDefaultRegistry(PoolingHttpClientConnectionManager.java:114)
	at org.apache.http.impl.conn.PoolingHttpClientConnectionManager.<init>(PoolingHttpClientConnectionManager.java:121)
	at com.thunisoft.dzjz.commons.http.client.HttpClient.<clinit>(HttpClient.java:84)
	... 37 more
Caused by: java.security.NoSuchAlgorithmException: class configured for SSLContext: sun.security.ssl.SSLContextImpl$TLSContext not a SSLContext
	at sun.security.jca.GetInstance.checkSuperClass(GetInstance.java:260)
	at sun.security.jca.GetInstance.getInstance(GetInstance.java:237)
	at sun.security.jca.GetInstance.getInstance(GetInstance.java:164)
	at javax.net.ssl.SSLContext.getInstance(SSLContext.java:156)
	at org.apache.http.ssl.SSLContexts.createDefault(SSLContexts.java:51)
	... 41 more

在测试类上加上下面注解

@PowerMockIgnore("javax.net.ssl.*")
  • 1
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值