导航:首页 > 方法技巧 > 方法中有新建对象如何mock

方法中有新建对象如何mock

发布时间:2023-06-10 18:24:09

A. 怎么mockito方法的内部对象

怎么mockito方法的内部对象?Mockito是一个针对Java的mocking框架。它与EasyMock和jMock很相似,但是通过在执行后校验什么已经被调用,它消除了对期望行为(expectations)的需要。其它的mocking库需要你在执行前记录期望行为(expectations),而这导致了丑陋的初始化代码。下文为转载,但原文有问题,错误的地方特地标红了

Introction
Code in which new objects are created can be difficult to test. There are a number of patterns for doing this; two of them are discussed here. Both of these patterns may require rearranging your code a little, to make it more testable. Writing code that's easily testable is a good thing to be doing, regardless of which mocking framework you end up using.

Details
Pattern 1 involves factoring uses of new into one-line methods, then using a Mockito spy. This is the simpler of the two patterns. Pattern 2 involves factoring uses of new into a separate class and injecting it. It's a little more work, but it can be more powerful. The new calls that you want to factor out (using either pattern) are those where an object is created, that you are likely to want to mock. It is recommended that you use one or other of these patterns, whenever you find yourself writing new, on a class that's in your code base (as opposed to a JDK class or a class from a third party library).

B. 使用Powermock对私有方法进行mock

 团誉宏 在public方法中往往会调用一些private方法,如果private方法很复杂,我们就需要处理很多方法的mock。如果这时只想要测试public方法,并不想关注private方法的逻辑,那么就需要虚历对private方法进行mock。下面我们简单介绍下如何通过Powermock来对私有方法进行mock。

被测试类:

  此类中包含一个public方法mockPrivateFunc,里面调用了private方法privateFunc。当前我们想要测试该public方法,并且不想进入private方法执行,那么就需要对该塌册私有方法进行模拟。

测试类:

  1、由于是对本类的私有方法进行模拟,所以需要在PrepareForTest后面加上MockPrivateClass,同时需要使用spy来模拟一个对象。
  2、 使用下面方式来模拟私有方法:

  如果私有方法存在参数,则同样的需要在私有方法名后面带上同样个数及类型的参数,其方法原型为:

  3、使用verifyPrivate来验证私有方法被调用,其例如下:

  verifyPrivate的参数为mock的对象,及验证模式(可选),invoke参数为要验证的私有方法名称及相应参数。

C. 如何mock静态方法

因为Mockito使用继承的方式实现mock的,用CGLIB生成mock对象代替真实的对象进行执行,为了mock实例的方法,你可以在subclass中覆盖它,而static方法是不能被子类覆盖的,所以Mockito不能mock静态方法。
但PowerMock可以mock静态方法,因为它直接在bytecode上工作,类似这样:
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.moles.testng.PowerMockTestCase;
import org.testng.Assert;
import org.testng.annotations.Test;
@PrepareForTest(AbstractAnimal.class)
public class AbstractAnimalTest extends PowerMockTestCase {

阅读全文

与方法中有新建对象如何mock相关的资料

热点内容
最简单的断食排毒方法 浏览:677
经济研究方法课程内容 浏览:238
iphone屏幕坏了按不动解决方法 浏览:997
解一元二次方程配方法教案视频 浏览:889
无法菠萝手工制作方法图片 浏览:102
锻炼的具体方法 浏览:651
隐藏式马桶安装方法图水路高度 浏览:650
如何根据种子的特性确定播种方法 浏览:262
用什么方法可以让蟹爪兰开花 浏览:687
鉴别老白茶的几种方法 浏览:981
penalty分析方法 浏览:832
怎么洗头最快方法 浏览:221
七相色谱常用的定性方法有 浏览:237
电脑恢复速度最快方法 浏览:471
中药拔罐的功效与作用及食用方法 浏览:359
教学方法的启发式 浏览:143
不正确洗手方法的图片 浏览:465
制备氨气的有哪些方法 浏览:353
扁平疣药物治疗方法 浏览:490
数字图片的制作方法 浏览:92