我有以下简单的测试用例,使用 powermock 通过模拟 Random 对象的创建来模拟从
ExceptionClass.getRandom
的方法抛出异常。
但是,从测试结果来看,
obj.getRandom()
返回随机值,因此Assert.assertTrue(obj.getRandom() == 111)
失败,但我认为obj.getRandom()
应该通过模拟随机创建并抛出异常返回111。
package com.example;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.powermock.modules.junit4.PowerMockRunner;
import static org.powermock.api.mockito.PowerMockito.*;
import java.util.Random;
class ExceptionClass {
public int getRandom() {
try {
//Mock the random object using whenNew(Random.class).withNoArguments()
Random random = new Random();
//random.nextInt should throw IllegalStateException,so that 111 is returned
return random.nextInt();
} catch (Exception e) {
return 111;
}
}
}
@RunWith(PowerMockRunner.class)
public class MockThrowExceptionTest {
@InjectMocks
ExceptionClass obj;
@Test
public void testGetRandom() throws Exception {
Random rand = mock(Random.class);
whenNew(Random.class).withNoArguments().thenReturn(rand);
when(rand.nextInt()).thenThrow(new IllegalStateException());
//An exception is thrown in ExceptionClass.getRandom method, so that 111 should be returned,but it is a random value
Assert.assertTrue(obj.getRandom() == 111);
}
}
您可以使用
mockito-inline
模拟构造函数。
所需依赖
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-inline</artifactId>
<version>5.2.0</version>
<scope>test</scope>
</dependency>
这是一个使用示例
@Test
public void testGetRandom() throws Exception {
try (var m = mockConstruction(Random.class,
(mock, context) -> {
when(mock.nextInt()).thenReturn(111);
})) {
Random r = new Random();
assertEquals(111, r.nextInt());
}
}