【问题标题】:Junit test case in spring bootSpring Boot 中的 Junit 测试用例
【发布时间】:2020-12-29 16:32:37
【问题描述】:

如何为 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测试请建议我..

【问题讨论】:

标签: java spring-boot junit4


【解决方案1】:

对不起,我为 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 类中实现equals()hashCode(),或者另一个选项可以在你关心的Demo 的字段上断言。我也不确定您调用getName()cart 是什么,但如果它是您的服务的另一个依赖项,您必须将其作为模拟注入并使用when() 正确设置并返回值。

在 junit4/5 方面的差异应该是(不是 100% 肯定是所有的,这里是我的记忆):

  • 进口
  • @ExtendWith 应该是 @RunWith(mockitojunitrunner.class)
  • 异常测试应该是@Test(expected = ApiError.class),而不是使用assertThrows

【讨论】:

    【解决方案2】:

    如果存储库中的数据不可用,此功能基本上会保存数据,Junits 旨在检查此功能是否按预期工作。在这里你将测试2个案例

    1. 当存储库中的数据可用时:对于这个模拟 repository.existsByNameAndAge(...) 并返回 false ,在测试用例中使用预期@Test(expected=ApiError.class)

    2. 如果不是:在这种情况下使用与上述情况相反的情况,不要使用预期的属性。

    【讨论】:

      猜你喜欢
      • 2018-02-23
      • 2021-07-26
      • 2019-10-26
      • 1970-01-01
      • 2017-06-06
      • 1970-01-01
      • 1970-01-01
      • 2018-12-24
      • 1970-01-01
      相关资源
      最近更新 更多