mockito、easymock、powermock使用(7)-whenNew使用

目的

编写whenNew测试代码,模拟新建对象其方法的执行结果

准备工作

mockito、easymock、powermock使用(2)-准备工作

测试代码

import com.suning.work.controller.MockController;
import junit.framework.TestCase;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.MockitoAnnotations;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import java.io.File;

@RunWith(PowerMockRunner.class)
@PowerMockIgnore("javax.management.*")
public class MockWhenNewTest extends TestCase {
    @InjectMocks
    MockController mockController;

    @Before
    public void setUp() throws Exception {
        MockitoAnnotations.initMocks(this);
    }

    /**
     * 当使用PowerMockito.whenNew方法时,必须加注解@PrepareForTest和@RunWith。
     * 注解@PrepareForTest里写的类是需要mock的new对象代码所在的类
     *
     * PrepareForTest 可以写在测试类或测试函数上效果一样
     * @throws Exception
     */
    @Test
    @PrepareForTest(MockController.class)
    public void test() throws  Exception {

        File file = PowerMockito.mock(File.class);
        //模拟创建新对象的返回值
        PowerMockito.whenNew(File.class).withArguments("system.properties").thenReturn(file);
        //模拟方法的结果
        PowerMockito.when(file.exists()).thenReturn(true);
        boolean result= mockController.fileExist("system.properties");
        System.out.println(result);

        PowerMockito.when(file.exists()).thenReturn(false);
        result= mockController.fileExist("system.properties");
        System.out.println(result);
    }
}

测试说明

/**
 * 当使用PowerMockito.whenNew方法时,必须加注解@PrepareForTest和@RunWith。
 * 注解@PrepareForTest里写的类是需要mock的new对象代码所在的类
 *
 * PrepareForTest 可以写在测试类或测试函数上效果一样
 */
@PrepareForTest(MockController.class)
//模拟创建新对象的返回值
PowerMockito.whenNew(File.class).withArguments("system.properties").thenReturn(file);
//模拟方法的结果
PowerMockito.when(file.exists()).thenReturn(true);

测试结果

true
false

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值