Mockito 使用注解来初始化的代码片断 例子

来源:互联网 发布:千千静听 mac 老版本 编辑:程序博客网 时间:2024/06/06 16:38

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(10);        Thread.sleep(100);        HealthReport anotherHealthReport = healthService.getHealthReport();        assertThat(anotherHealthReport.isAvailable(), is(false));    }}
0 0
原创粉丝点击