简体   繁体   English

带有私有字段的void方法的单元测试-线路覆盖率

[英]Unit Test of void method with private fields - Line Coverage

I have the following code in my void method in ClassUnderTest class 我在ClassUnderTest类的void方法中有以下代码

public void doSomething(){

    A a = new A();
    a.setAb("b");
    a.setAc("c");

    persistantObject.commitObj(a);
}

I know how to write a passing JUnit, however, I can't figure out how to get a 100% line coverage. 我知道如何编写传递的JUnit,但是,我不知道如何获得100%的行覆盖率。

I've attempted the following 我尝试了以下

@Mock
private PersistantObject mockPersistantObject;
public void testDoSomething(){

    EasyMock.createMock(this);
    ClassUnderTest classUnderTest = new ClassUnderTest();
    ReflectionTestUtils.setField(classUnderTest, "persistantObject", mockPersistantObject);

    A a = new A();
    a.setAb("b");
    a.setAc("c");

    mockPersistantObject.commitObj(a);
    EasyMock.expectLastCall();

    EasyMock.replay(this);
    classUnderTest.doSomething();
    ...
    EasyMock.verify(this);
}

UnitTesting is not about line coverage. UnitTesting与线路覆盖率无关

UnitTesting is about requirement coverage. 单元测试是关于需求范围的。

Line coverage is just a tool to get a feeling about how much of the requirements already implemented might be covered. 线路覆盖范围只是一种工具,用于了解可能已经覆盖了多少已实施的需求

So don't care too much about the LoCs covered by your test but look for behavior in your requirements , that needs a certain behavior of your cut and check if that is covered by a test. 因此,不必太在乎测试所涵盖的LoC,而是在您的需求中寻找行为 ,该行为需要您剪切的某种行为 ,并检查测试是否涵盖了行为


Furthermore UnitTests do not care about LoCs for another reason: The LoCs are subject to change during refactoring and evolving the application. 此外,UnitTest也不关心LoC的另一个原因:在重构和发展应用程序过程中,LoC可能会发生变化。 Therefore any effort you may do to increase the line coverage will either lead to breaking test or prevent the required changes (depending on your confidence in your tests and or your skills). 因此,您为增加线路覆盖率所做的任何努力都会导致测试中断或阻止所需的更改(取决于您对测试和/或技能的信心)。 But Unittests should only fail if the behavior changes, not the code implementing it. 但是,只有行为改变时,单元测试才应该失败,而不是实现它的代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM