【问题标题】:JUnit test for my method我的方法的 JUnit 测试
【发布时间】:2018-12-22 04:40:35
【问题描述】:

大家好,我需要为我的方法编写单元测试。我遇到了一些麻烦,因为我是 JUnit 的新手。我需要为此方法编写一个测试。 这是我的方法

@Override
public Long countSellingOrdersInQueue(String principal) {
    List<String> states = Arrays.asList(PENDING.name(), REGULARIZED.name());
    return orderRepository.countByArticleUserIdAndStateIn(principal, states);
}

我尝试了,但我被阻止了,这是我的结果

附:测试通过了,但我不明白我的测试是否正确

@MockBean
private OrderRepository orderRepository;

private String principal ;

@Test
public void countSellingOrdersInQueueTest(){
    orderService.countSellingOrdersInQueue(principal);
    List<String> states = Arrays.asList(PENDING.name(), REGULARIZED.name());
    orderRepository.countByUserIdAndStateIn(principal,states);
}

【问题讨论】:

  • 为什么要在测试中复制被测方法的代码?如果您真的必须这样做,那将是难以置信的脆弱:如果您更改代码而不更改测试怎么办?测试应该调用方法本身。
  • 你好,安迪,谢谢你的评论 :) 那么完美的解决方案是什么?
  • 你对编写单元测试的理解显然有一些基本的差距。我建议您在担心“完美解决方案”之前花时间阅读一些教程。

标签: java unit-testing junit


【解决方案1】:

在您的情况下,它只是单元测试,您不需要使用@MockBean,因为它会加载上下文。单元测试旨在更快地运行,使用@MockBean,将加载上下文并需要时间来完成测试。 Here 是关于何时使用@Mock 以及何时使用@MockBean 的建议。

正如 Maxim 所说,测试中没有断言。这就是测试没有失败的原因。

编写测试时要记住的几件事。

  • 测试被视为代码的文档,它应该更具可读性,以便其他人理解代码。
  • 如前所述,单元测试是为了提供更快的反馈
  • 在测试中具有 AAA(排列、动作、断言)结构。更多信息here

代码如下:

public class OrderServiceTest {

    @InjectMocks
    private OrderService orderService;

    @Mock
    private OrderRepository orderRepository;

    @Before
    public void setUp() throws Exception {
        initMocks(this);
    }

    @Test
    public void countSellingOrdersInQueueTest(){
        when(orderRepository.countByArticleUserIdAndStateIn(any(), any())).thenReturn(1L);
        String principal = "dummyString";

        Long actualCount = orderService.countSellingOrdersInQueue(principal);

        List<String> expectedStates = Arrays.asList("State 1", "State 2");
        assertThat(actualCount, is(1L));
        verify(orderRepository).countByArticleUserIdAndStateIn(principal, expectedStates);
    }
}

【讨论】:

  • 好答案!当提到 unit test verify behavior,not code... 时会很完美
  • 谢谢蒂莫西!!抱歉,实际上无法理解你的意思。你能解释一下吗?会相应更新
  • 请参考我的这个答案:stackoverflow.com/a/51153233/7023245希望它足够清楚。
【解决方案2】:

测试通过,因为您没有任何检查结果的断言。您只需调用无异常执行的方法。

简单测试示例:

    @Test
    public void test() {
        assertEquals(true, true);
    }

在您的情况下,测试将如下所示:

    @Test
    public void countSellingOrdersInQueueTest(){
        orderService.countSellingOrdersInQueue(principal);
        List<String> states = Arrays.asList(PENDING.name(), REGULARIZED.name());
        orderRepository.countByUserIdAndStateIn(principal,states);
        assertEquals(10, orderRepository.countByUserIdAndStateIn(principal,states));//10 replace to expectetion count
        //add some more checks
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-01-07
    • 1970-01-01
    • 2021-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多