initMocks(this); 这句话的意思是初始化所有需要mock的对象,这些对象是使用@Mock注解所定义的
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.mockito.Mockito.when;
import static org.mockito.MockitoAnnotations.initMocks;
public class HealthServiceTest {
@Mock
private MetricsClient metricsClient;
@Mock
private SequenceService sequenceService;
@Mock
private MetricsFormatter metricsFormatter;
HealthService healthService;
@Before
public void setUp() throws Exception {
initMocks(this);
healthService = new HealthService(new SystemStatus(new SDAStatus(true, true)), metricsClient, metricsFormatter, sequenceService);
}
@Test
public void willReturnAvailable() throws Exception {
when(sequenceService.isHealth()).thenReturn(true);
HealthReport healthReport = healthService.getHealthReport();
assertThat(healthReport.isAvailable(), is(true));
}
@Test
public void willReturnUnavailableAfterTimeout() throws Exception {
HealthReport healthReport = healthService.getHealthReport();
assertThat(healthReport.isAvailable(), is(true));
healthService.setHealthReportTimeout();
Thread.sleep();
HealthReport anotherHealthReport = healthService.getHealthReport();
assertThat(anotherHealthReport.isAvailable(), is(false));
}
}