準備技術:
為什麼會有Mock?
Mockito (the combination of the PowerMock and Mockito frameworks is called PowerMockito) 就是專門做這件事情。
先看程式。
public class SystemStatusService {
public static String getValue() {
return "Offline";
}
}
public class SystemStatusLayout extends HorizontalLayout {
private Label lblSystemStatus;
public SystemStatusLayout() {
String value = SystemStatusService.getValue();
lblSystemStatus = new Label(value);
addComponent(lblSystemStatus);
}
public Label getLblSystemStatus() {
return lblSystemStatus;
}
}
這是我們要測試的類別。
測試程式如下:我們透過一個@RunWith(PowerMockRunner.class) 呼叫測試框架,能夠Mock進去。注意其中一行 PowerMockito.mockStatic(SystemStatusService.class) 就是測試Static方法。
@RunWith(PowerMockRunner.class)
@PrepareForTest({SystemStatusService.class})
public class SystemStatusLayoutTest {
private SystemStatusLayout layout;
@Before
public void setUp() throws Exception {
PowerMockito.mockStatic(SystemStatusService.class);
Mockito.when(SystemStatusService.getValue()).
thenReturn("Online");
layout = new SystemStatusLayout();
}
@Test
public void isSystemStatusShown() {
Label lblSystemStatus = layout.getLblSystemStatus();
String value = lblSystemStatus.getValue();
Assert.assertEquals("Online", value);
}
}
測試結果,如圖。
參考資料
Day19 結束