一、为什么要用powermock?
- 能对private/static/final等方法mock
- 支持mock的对象是在方法内部new出来的Mock
二、powermock的使用
1、 maven依赖
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-module-junit4</artifactId>
<version>2.0.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-api-mockito2</artifactId>
<version>2.0.0</version>
<scope>test</scope>
</dependency>
2、springboot基础配置(测试基类)
@PreparwForeTest({被mock的静态方法})
@RunWith(PowerMockRunner.class)
@PowerMockRunnerDelegate(SpringJUnit4ClassRunner.class)
@PowerMockIgnore({"javax.net.ssl.*", "javax.management.*", "javax.crypto.*"})
@SpringBootTest
public class BasePowerMock {}
3、mock对象
1)@Mock和@MockBean
- @Mock(需要MockAnotation.init(this)初始化: 完全mock一个对象
等于Mockito.mock(Object.class) - @MockBean:mock对象替换Spring容器中的同样类型的bean
2)@Spy和@SpyBean
- @Spy:不打桩,则与普通对象一样
- @SpyBean:不打桩,则与Spring中的bean一样
4、stub
1)目标对象的public方法
Mockito.doReturn(new Object())
.when(userService).doSome(Mockito.anyInt());
Mockito.doNothing
.when(userService).doSome(Mockito.anyInt());
Mockito.doThrows(new RuntimeException())
.when(userService).doSome(Mockito.anyInt());
2)目标对象的static、final、private方法
-
- @PrepareForTest({目标1.class,目标2.class})
-
- PowerMockito.static(目标.class)
-
- PowerMockito.doNothing().when(目标.class,“methodName”,Mockito.anyInt());
https://www.jianshu.com/p/44fcadaf041d
4、verify
1) 方法调用次数
2)断言异常
|