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 {