Is it important to unit test a constructor?

前端 未结 15 1560
一生所求
一生所求 2020-12-08 01:54

Ought I to unit test constructors? Say I have a constructor like this:

IMapinfoWrapper wrapper;
public SystemInfo(IMapinfoWrapper mapinfoWrapper)
{
    this.         


        
相关标签:
15条回答
  • 2020-12-08 02:24

    Yes. If you have logic in your constructor, you should test it. Simply setting properties is not logic IMO. Conditionals, control flow, etc IS logic.

    Edit: You should probably test for when IMapinfoWrapper is null, if that dependency is required. If so, then that is logic and you should have a test that catches your ArgumentNullException or whatever... your tests are specifications that define how the code behaves. If it throws an ArgumentNullException, then that should be specified in a test.

    0 讨论(0)
  • 2020-12-08 02:25

    If the constructor contains some logic, such as initialize a class, I think you should test the very constructor. Or you can talk to the developer that putting initialization in the constructor will cut the testability of code under test.

    0 讨论(0)
  • 2020-12-08 02:26

    Q: If you are setting a member variable in the constructor, why are you setting it.

    A: Because you have a failing unit test that can only be made to pass by setting it in the constructor.

    If you use this logic, where you only write code to cause a unit test to pass (Test Driven Development), then you will already have the answer to your question.

    0 讨论(0)
提交回复
热议问题