如何在JUnit中的单独方法中测试long方法?

时间:2015-08-23 17:10:08

标签: junit mockito

我有一个很长的公共方法。它清楚地将逻辑分成不同的部分。我可以做些什么来测试它就像是

@Test
public void shouldWork() {
    //Execute target method

    //This is a comment hinting that now the first step is verified
    //Verify first step

    //This is a comment hinting that now the second step is verified
    //Verify second step
}

我根本不喜欢这样,因为如果任何一个部分出现错误,它只会在这个巨大的方法中显示失败。为每一步编写单独的测试方法似乎是合理的。然后我面临以下情况:

@Test
public void testFirstStep() {
    //Execute target method
    //Verify first step
}

@Test
public void testSecondStep() {
    //Execute target method
    //Verify second step
}

这里我遇到的问题是,我对两个步骤的验证都采用verify(myMockitoMock).myMethod(myArg)形式(在同一个模拟上多次)。由于这些验证确实尊重了第一步的调用顺序,但第二步的测试假定第一步的所有验证都已经发生。从逻辑上讲,这样做很好

@Test
public void testFirstStep() {
    //Execute target method
    executeVerificationsForFirstStep(myMock);
}

@Test
public void testSecondStep() {
    //Execute target method
    executeVerificationsForFirstStep(myMock);
    //Verify second step
}

private void executeVerificationsForFirstStep(Mock myMock) {
    //Verifications for first step on myMock
}

然而,如果第一步验证失败,则第二次测试的测试将失败。

有什么建议吗?

1 个答案:

答案 0 :(得分:0)

首先写下让你不开心的测试...

@Test
public void shouldWork() {
    //Execute target method

    //This is a comment hinting that now the first step is verified
    //Verify first step

    //This is a comment hinting that now the second step is verified
    //Verify second step
}

然后确保它通过并验证有用的东西。请记住一个类应该有一个责任而一个方法应该做一个事情的经验法则。提取您已经可以看到的明显方法。重新运行测试并确保它通过。

现在评估类和方法相对于这两个经验法则的作用。班级有责任吗?如果没有,那么考虑一下责任是什么,并编写一些测试来创建新的类来履行这些职责。如果你以这种方式工作(TDD),我怀疑你的方法会更频繁地做一个事情,甚至不用考虑那个规则。