Mockito PowerMock 静态 方法 @Spy 对象方法 mock

import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Matchers;
import org.mockito.Mock;
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;


/*
* 注意,我用junit,没有用testng
*/
@RunWith(PowerMockRunner.class)
@PrepareForTest({FileUtils.class, RestHttpClient.class, StudentHonorUtil.class})
@PowerMockIgnore({"javax.management.*"})
public class XxxServiceImplTest {
@Mock
    MessageService messageService;

@InjectMocks
    @Spy //@Spy修饰的对象必须要手动new出来
X1ServiceImpl x1Service = new X1ServiceImpl();

@InjectMocks //非@Spy修饰的对象,可以不手动new,由mockito框架维护
X2ServiceImpl x2Service;

@BeforeClass //类初始化时,只调用一次
    public static void beforeClass(){


    }


    @Before //每运行一个testMethod,就运行一次
    public void before(){
        //对static方法的mock,必须放这里
        //如果放到beforeClass,单元测试不能通过,虽然看上去,此类所有单元测试前,只运行一次就行,但实际不行
        PowerMockito.mockStatic(FileUtils.class);
        PowerMockito.mockStatic(RestHttpClient.class);
        PowerMockito.mockStatic(StudentHonorUtil.class);
        MockitoAnnotations.initMocks(this);//此行根据实际情况自己安排放吧
    }

@Test
    public void method1Test() throws Exception {
        Mockito.doReturn(new Xxx()).when(x1Service).someMethod();//注意,对@Spy对象,必须这样mock
        Mockito.when(x2Service.someMethod(Matchers.anyString(), Matchers.anyInt())).thenReturn(new LinkedList<XObject>());

Mockito.verify(x2Service, Mockito.times(0)).someMethod(Matchers.anyString(), Matchers.anyString());
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值