您的位置:首页 > 编程语言

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

2016-09-05 14:03 495 查看
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));
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  mock