我在服務層中有一種方法可以將專案保存到資料庫。該方法首先檢查資料庫中是否存在同名專案。如果有,那么它會拋出一個帶有訊息的例外,如果沒有,那么它只是保存新專案。這是代碼;
public TodoList saveTodoList(TodoList todoList) {
List<TodoList> match = StreamSupport.stream(getAllTodoLists().spliterator(), false)
.filter(list -> list.getName().equals(todoList.getName()))
.collect(Collectors.toList());
if (match.size() > 0)
throw new ExistingDataException("Todo List already exists!");
else
return todoListRepository.save(todoList);
}
我正在嘗試學習使用 JUnit 5 和 Mockito 進行測驗,但我對一般要測驗的內容有點困惑。我應該為此方法撰寫多少個測驗?我需要測驗流(我什至不知道如何)?您如何決定在方法中測驗什么?
編輯:這是我的測驗類和保存方法的測驗方法;
@ExtendWith(MockitoExtension.class)
class TodoListServiceTest {
@Mock
private ITodoListRepository todoListRepository;
@InjectMocks
private TodoListService todoListService;
@Test
@DisplayName("Should save the list to the repository")
public void whenGivenTodoListDoesNotExistInDatabase_ThenSaveNewList() {
TodoList mockList = mock(TodoList.class);
mockList.setId(1);
mockList.setName("List 1");
when(todoListRepository.save(any(TodoList.class))).thenReturn(mockList);
TodoList actual = todoListService.saveTodoList(mockList);
assertEquals(mockList.getId(), actual.getId());
assertEquals(mockList.getName(), actual.getName());
}
@Test
@DisplayName("Should throw exception if there is a list with given item's name")
public void shouldThrowExistingDataException_IfThereIsAList_WithTheSameName() {
TodoList mockList = mock(TodoList.class);
mockList.setId(1);
mockList.setName("List 1");
Throwable actualException = assertThrows(ExistingDataException.class,
() -> {
todoListService.saveTodoList(mockList);
});
assertTrue(actualException.getMessage().contains("Todo List already exists!"));
}
uj5u.com熱心網友回復:
我將嘗試回答您提出的一些問題:
我應該為此方法撰寫多少個測驗?:本質上,在為一個函式或一段代碼撰寫測驗用例時,你應該撰寫多少個測驗用例是沒有限制的。通常,您嘗試測驗至少 1 個正流和 1 個負流。如果您的一段代碼有很多邊緣情況,那么可能也要檢查這些情況。
我需要測驗流(我什至不知道如何)?:不。 Stream 是內置的 java 功能,您不測驗內置功能。你只是測驗你的邏輯。
您如何決定在方法中測驗什么?:正如我之前提到的,您通常會測驗正流和負流,包括任何邊緣情況。對于上述功能,您似乎有 1 個正流和 1 個負流。您的積極情況可能是您希望資料庫中不存在值并成功存盤資料,而消極情況可能是當該資料已經存在時您會拋出例外。這是您應該撰寫的兩個最小測驗用例。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/464430.html
