xml<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-all</artifactId>
<version>1.10.19</version>
<scope>test</scope>
</dependency>
</dependencies>
javapublic class ListTest {
@Test
public void letsMockListSize() {
List list = mock(List.class);
when(list.size()).thenReturn(10);
assertEquals(10, list.size());
}
@Test
public void letsMockListSizeWithMultipleReturnValues() {
List list = mock(List.class);
when(list.size()).thenReturn(10).thenReturn(20);
assertEquals(10, list.size()); // First Call
assertEquals(20, list.size()); // Second Call
}
@Test
public void letsMockListGet() {
List<String> list = mock(List.class);
when(list.get(0)).thenReturn("in28Minutes");
assertEquals("in28Minutes", list.get(0));
assertNull(list.get(1));
}
@Test(expected = RuntimeException.class)
public void letsMockListGetToThrowException() {
List<String> list = mock(List.class);
when(list.get(Mockito.anyInt())).thenThrow(
new RuntimeException("Something went wrong"));
list.get(0);
}
@Test
public void letsMockListGetWithAny() {
List<String> list = mock(List.class);
Mockito.when(list.get(Mockito.anyInt())).thenReturn("in28Minutes");
// If you are using argument matchers, all arguments
// have to be provided by matchers.
assertEquals("in28Minutes", list.get(0));
assertEquals("in28Minutes", list.get(1));
}
@Test
public void bddAliases_UsingGivenWillReturn() {
List<String> list = mock(List.class);
//given
given(list.get(Mockito.anyInt())).willReturn("in28Minutes");
//then
assertThat("in28Minutes", is(list.get(0)));
assertThat("in28Minutes", is(list.get(0)));
}
}
见转载
java @Test
public void captureArgument() {
ArgumentCaptor<String> argumentCaptor = ArgumentCaptor
.forClass(String.class);
TodoService todoService = mock(TodoService.class);
List<String> allTodos = Arrays.asList("Learn Spring MVC",
"Learn Spring", "Learn to Dance");
Mockito.when(todoService.retrieveTodos("Ranga")).thenReturn(allTodos);
TodoBusinessImpl todoBusinessImpl = new TodoBusinessImpl(todoService);
todoBusinessImpl.deleteTodosNotRelatedToSpring("Ranga");
Mockito.verify(todoService).deleteTodo(argumentCaptor.capture());
assertEquals("Learn to Dance", argumentCaptor.getValue());
}
xml <dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-library</artifactId>
<version>1.3</version>
<scope>test</scope>
</dependency>
javaimport static org.hamcrest.CoreMatchers.hasItems;
assertThat(scores, hasSize(4));
assertThat(scores, hasItems(100, 101));
assertThat(scores, everyItem(greaterThan(90)));
assertThat(scores, everyItem(lessThan(200)));
// String
assertThat("", isEmptyString());
assertThat(null, isEmptyOrNullString());
本文作者:问海
本文链接:
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!