微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

spring boot中的junit测试用例

如何解决spring boot中的junit测试用例

如何为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",10));
        verify(newRepository,times(1)).save(demoCaptor.capture());
        final Demo actual = captor.getValue();
        final Demo expected = //create your expected here
        assertEquals(expected,actual);
    }

请记住在您的 equals() 类中实现 hashCode()Demo,否则其他选项可能会在您关心的 Demo 字段上进行断言。我也不确定您正在调用 cartgetName() 是什么,但如果它是您服务的另一个依赖项,您必须将其作为模拟注入并使用 {{1} 正确设置它}} 和返回值。

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

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

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

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

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。