我在 Spring Boot 示例中使用 Mockito 撰寫 JUnit 服務時遇到問題。
我得到了結果的空指標例外,因為它有空值。
我該如何解決這個問題?
這是下面顯示的代碼片段。
這是Category的服務類
@Service
@RequiredArgsConstructor
public class CategoryService {
private final CategoryRepository categoryRepository;
public Category findCategory(Long id) {
return categoryRepository.findById(id).orElseThrow();
}
public Category findByName(String value) {
return categoryRepository.findByName(value).orElseThrow();
}
}
這是如下所示的 JUnit Service 類
@ExtendWith(MockitoExtension.class)
public class CategoryServiceTest{
@Mock
private CategoryService categoryService;
@Mock
private CategoryRepository categoryRepository;
@Test
void givenCategory_whenLoadCategory_thenReturnCategory() {
// given - precondition or setup
Category category = Category.builder().name("Category 1").build();
// when - action or the behaviour that we are going test
when(categoryRepository.findById(anyLong())).thenReturn(Optional.of(category));
Category result = categoryService.findCategory(anyLong()); // return null
// then - verify the output
assertEquals(category.getName(), result.getName());
}
@Test
void givenCategory_whenFindByName_thenReturnCategory() {
Category category = Category.builder().name("Category 1").build();
// when - action or the behaviour that we are going test
when(categoryRepository.findByName("Category 1")).thenReturn(Optional.of(category));
Category result = categoryService.findByName("Category 1"); // return null
// then - verify the output
assertEquals(category.getName(), result.getName());
}
}
uj5u.com熱心網友回復:
你在嘲笑被測類,應該是
@ExtendWith(MockitoExtension.class)
public class CategoryServiceTest{
@InjectMocks
private CategoryService categoryService;
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/513239.html
標籤:爪哇弹簧靴朱尼特模仿者
