mock问题记录

1.添加依赖

 <dependency>
            <groupId>org.powermock</groupId>
            <artifactId>powermock-api-mockito2</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.javassist</groupId>
                    <artifactId>javassist</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.powermock</groupId>
            <artifactId>powermock-module-junit4</artifactId>
            <scope>test</scope>
        </dependency>
         <dependency>
            <groupId>org.mockito</groupId>
            <artifactId>mockito-core</artifactId>
            <scope>test</scope>
        </dependency>

2.下载testMe插件并设置对应模版

#parse("TestMe macros.java")
#set($hasMocks=$MockitoMockBuilder.hasMockable($TESTED_CLASS.fields))
#if($PACKAGE_NAME)
package ${PACKAGE_NAME};
#end

import org.junit.Assert;
import org.junit.Test;
#if($hasMocks)
import org.junit.Before;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import com.cainiao.config.LightBaseTest;
//import static org.mockito.Mockito.*;
#end

#parse("File Header.java")
public class ${CLASS_NAME} extends LightBaseTest{
#renderMockedFields($TESTED_CLASS.fields)
#renderTestSubjectInit($TESTED_CLASS,$TestSubjectUtils.hasTestableInstanceMethod($TESTED_CLASS.methods),$hasMocks)
#if($hasMocks)

    @Before
    public void setUp() {
        MockitoAnnotations.initMocks(this);
    }
#end
#foreach($method in $TESTED_CLASS.methods)
#if($TestSubjectUtils.shouldBeTested($method))

    @Test
    public void #renderTestMethodName($method.name)() throws Exception {
#if($MockitoMockBuilder.shouldStub($method,$TESTED_CLASS.fields))
#renderMockStubs($method,$TESTED_CLASS.fields)

#end
        #renderMethodCall($method,$TESTED_CLASS.name)
#if($method.hasReturn())        Assert.#renderJUnitAssert($method)#end
    }
#end
#end
}

#parse("TestMe Footer.java")

3.进去需要mock的类并右键生成对应test方法

这时会生成对应的类并继承LightBaseTest,我们在这里写对应常用的方法

4.不同情况下的mock的使用方法

1.碰到编程式事务(写在LightBaseTest类中)
initTransaction();
 protected void initTransaction() {
        when(transactionTemplate.execute(any())).thenAnswer(new Answer() {
            public Object answer(InvocationOnMock invocation) {
                Object[] args = invocation.getArguments();
                TransactionCallback arg = (TransactionCallback) args[0];
                return arg.doInTransaction(new SimpleTransactionStatus());
            }
        });
    }

2.碰到静态方法块

测试父类中添加方法

    /**
     *  mock静态类
     * tips:注意加载次序,与书写次序保持一致
     */
    protected void initPowerMock() {
        PrepareForTest annotation = this.getClass().getAnnotation(PrepareForTest.class);
        for (Class<?> aClass : annotation.value()) {
            PowerMockito.mockStatic(aClass);
        }
    }
//1.加这两个注解
@RunWith(PowerMockRunner.class)
@PrepareForTest({demoTest.class})
public class test01 extends LightBaseTest {
    @Before
    public void setUp() {
        MockitoAnnotations.initMocks(this);
        //2.加这个方法
        initPowerMock();
    }

这种也可

MockedStatic<CollectionUtils> collectionUtilsMockedStatic = mockStatic(CollectionUtils.class);
        collectionUtilsMockedStatic.when(() -> CollectionUtils.isEmpty(anyCollection())).thenReturn(false);

3.碰到mybatis的example

错误提示:tk.mybatis.mapper.MapperException: 无法获取实体类

Config config = new Config();
EntityHelper.initEntityNameMap(xxxx.class, config);

4.碰到静态方法中出现静态代码块时

@SuppressStaticInitializationFor("xxx.xxx")

5.需要走进错误方法又需要单测成功的

thrown.expect(Exception.class);

6.mock有返回值及无返回值

doNothing().when(xxxxService).commitApply(any());
when(xxxxServiceWrapper.getByUserId(any())).thenReturn(xxxxDTO);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值