由于要代码中使用了 Date 类生成实时时间,单元测试中需要 Mock Date 的构造方法,以预设其行为,这就要使用到 PowerMock
在 Spring Boot 的测试套件中,需要添加 @RunWith(SpringRunner.class) 和 @SpringBootTest 注解。
但是 PowerMock 需要添加 @RunWith(PowerMockRunner.class) 注解。
@RunWith 注解只能有一个,解决方案是使用 @PowerMockRunnerDelegate 注解,同时使用 @PowerMockIgnore 注解避免报错:
@RunWith(PowerMockRunner.class)
@PowerMockRunnerDelegate(SpringRunner.class)
@PowerMockIgnore({"javax.management.*", "javax.net.ssl.*"})
@PrepareForTest({UsersService.class, Date.class})
@SpringBootTest
@Transactional
//@Rollback(false)
public class UsersServiceTest {
private Date date;
@Before
public void setUp() throws Exception {
PowerMockito.mock(Date.class);
PowerMockito.whenNew(Date.class).withNoArguments().thenReturn(date);
}
}