[英]Junit Test case Spring boot controller returning null value in ResponseEntity
[英]Junit test case in spring boot
我如何为 void 方法编写 junit 测试?
我在服务层有以下方法
@Override
public void add(Demo demo) throws ApiError {
if (!repository.existsByNameAndAge(demo.getName(), demo.getAge())) {
throw new ApiError(HttpStatus.BAD_REQUEST, "bad request");
}
Integer count = newRepository.countByName(cart.getName());
newRepository.save(new Demo(demo.getName(), demo.getAge(), demo.getCity(), count));
}
这是我的服务方法,我想为它做 junit 测试用例。 但它的返回类型是无效的。 我想对每个语句进行测试。 我该如何完成 junit 测试请建议我..
抱歉,我为 Junit5 写了答案,然后注意到您标记了 Junit4,无论如何我都会发布它,这个想法是相同的,代码中的差异应该很小。 您可以做的是使用 Mockito 注入模拟并验证方法是否使用您希望调用它们的参数来调用。 我会编写 2 个测试用例:一个用于检查是否引发异常并且未调用存储库,另一个用于检查存储库是否正确保存:
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.Mock;
import org.mockito.InjectMocks;
import org.mockito.junit.jupiter.MockitoExtension;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.Mockito.*;
@ExtendWith(MockitoExtension.class)
class MyServiceTest {
@Mock
private Repo repository;
@Mock
private NewRepo newRepository;
@Captor
private ArgumentCaptor<Demo> demoCaptor;
@InjectMocks
private MyService service;
@Test
void throwsIfDoesNotExistForGivenNameAndAge() {
when(repository.existsByNameAndAge("name", 12)).thenReturn(false);
assertThrows(ApiError.class, () -> service.add(new Demo("name", 12, "city", 10)));
verify(newRepository, times(0)).countByName(anyString());
verify(newRepository, times(0)).save(any(Demo.class));
}
@Test
void savesToNewRepositoryWithRightValues() {
when(repository.existsByNameAndAge("name", 12)).thenReturn(true);
when(newRepository.countByName("cart")).thenReturn(10);
service.add(new Demo("name", 12, "city", 10));
verify(newRepository, times(1)).save(demoCaptor.capture());
final Demo actual = captor.getValue();
final Demo expected = //create your expected here
assertEquals(expected, actual);
}
请记住在您的Demo
class 中实现equals()
和hashCode()
,或者其他选项可以在您关心的Demo
字段上进行断言。 我也不确定您调用getName()
的cart
是什么,但如果它是您服务的另一个依赖项,您必须将其作为模拟注入并使用when()
正确设置并返回值。
junit4/5 方面的差异应该是(不是 100% 确定它是全部,这里是我的 memory):
@ExtendWith
应该是@RunWith(mockitojunitrunner.class)
@Test(expected = ApiError.class)
而不是使用assertThrows
如果存储库中没有数据,则此 function 基本上会保存数据,Junits 旨在检查此 function 是否按预期工作。 在这里您将测试 2 个案例
当存储库中有数据可用时:对于这个模拟 repository.existsByNameAndAge(...) 并返回 false,在测试用例中使用预期的@Test(expected=ApiError.class)
如果不是:在这种情况下,使用与上述情况相反的情况,不要使用预期的属性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.