Spring Boot 2 實踐記錄之 Powermock 和 SpringBootTest

因爲要代碼中使用了 Date 類生成實時時間,單元測試中須要 Mock Date 的構造方法,以預設其行爲,這就要使用到 PowerMockjava

在 Spring Boot 的測試套件中,須要添加 @RunWith(SpringRunner.class) 和 @SpringBootTest 註解。單元測試

可是 PowerMock 須要添加 @RunWith(PowerMockRunner.class) 註解。測試

@RunWith 註解只能有一個,解決方案是使用 @PowerMockRunnerDelegate 註解,同時使用 @PowerMockIgnore 註解避免報錯:spa

@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);
  }
}
相關文章
相關標籤/搜索