junit测试用例

nimxete2  于 2021-06-29  发布在  Java
关注(0)|答案(2)|浏览(420)

如何为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测试用例。但它的返回类型是void。我想对每个站做测试。我怎样才能做这个junit测试请建议我。。

pdtvr36n

pdtvr36n1#

如果数据在存储库中不可用,这个函数基本上会保存数据,junits用来检查这个函数是否按预期工作。这里你将测试两个案例
当数据在存储库中可用时:对于此模拟存储库。existsbynameandage(…)并返回false,以供测试用例使用 @Test(expected=ApiError.class) 如果不是:在这种情况下,使用与上述情况相反的属性,不要使用预期的属性。

ctehm74n

ctehm74n2#

抱歉,我写了junit5的答案,然后注意到你标记了junit4,我将发布它无论如何,想法是相同的,代码中的差异应该是微小的。您可以使用mockito注入mock,并验证调用方法时是否使用了您希望调用的参数。我将编写两个测试用例:一个用于检查抛出的异常和未调用的存储库,另一个用于检查存储库是否正确保存:

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);
    }

记住实施 equals() 以及 hashCode() 在你的 Demo 类,或者另一个选项可以在 Demo 你关心我。我也不知道是什么 cart 您所拨打的电话 getName() 是的,但如果它是服务的另一个依赖项,则必须将其作为一个mock注入并正确地设置它 when() 和返回值。
junit4/5的区别应该是(不是100%确定都是它们,根据我的记忆):
进口
这个 @ExtendWith 应该是 @RunWith(mockitojunitrunner.class) 异常的测试应该是 @Test(expected = ApiError.class) 而不是使用 assertThrows

相关问题