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());
    }
}

猜你喜欢

转载自blog.csdn.net/collonn/article/details/79206166