例如要mock一个Util的静态方法getHalfLegs,如果输入参数是很简单时候,当然直接真实调用getHalfLegs即可。但如果输入是一个复杂的类Animal,而Animal就是一个mock,这时就需要mock此方法的输出了。
@RunWith(PowerMockRunner.class)
@PrepareForTest(Util.class)
public class VideoSpeechletStaticTest {
@Before
public void setup(){
PowerMockito.mockStatic(Util.class);
}
@Test
public void test_PlusOneLeg(){
// Arrange
when(Util.getHalfLegs(animal)).thenReturn(10);
// Act
int actual = underTest.plusOneLeg(animal);
// Assert
assertEquals(11, actual);
}
@InjectMocks
VideoSpeechlet underTest;
@Mock
Animal animal;
}
这三个粗体地方都要注意@PrepareForTest可以指定多个要mock的含静态方法的类。PowerMock用到两个lib:
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-module-junit4</artifactId>
<version>1.6.4</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-api-mockito</artifactId>
<version>1.6.4</version>
<scope>test</scope>
</dependency>
一定要注意版本一致,否则会出现奇怪错误。
ref:
https://blog.codecentric.de/en/2016/03/junit-testing-using-mockito-powermock/
No comments:
Post a Comment