1

Let's say we have a model class use to keep track of Fraud Checks:

class FraudCheck(object):

    def __init__(self, score_threshold):
        self.score = None
        self.transaction = None
        self.is_fraud = True
        self.score_threshold = score_threshold

Should we be writing unit tests for this __init__ method? There are other methods in the class as well.

So should we be writing tests similar to:

@pytest.fixture()
def fraud_data():
    account = FraudCheck(
        1000
    )
    return account


def test_fraud_data(fraud_data):
    assert fraud_data.score is None
    assert fraud_data.transaction is None
    assert fraud_data.is_fraud
    assert fraud_data.score_threshold == 10

I know this question was marked as a possible duplicate however the other question was a constructor setting on value. In this particular question, we are only setting one value but there are three other variables as well being set to default values. I would think a unit test would be appropriate in case the variables got mixed up during refactoring but I would like other peoples opinions.

user7692855
  • 1,582
  • 5
  • 19
  • 39
  • 2
    Possible duplicate of [Is it important to unit test a constructor?](https://stackoverflow.com/questions/357929/is-it-important-to-unit-test-a-constructor) – hoefling Aug 18 '18 at 22:14

2 Answers2

1

I had a def __init__(self): self.data = [1, 2] changed to self.data = [1, 2], by magic touch, It caused weird bug, I wish I has a type and value check for the __init__().

Gang
  • 2,658
  • 3
  • 17
  • 38
0

The trouble with the tests of simple constructors which set members to hard coded values is that they lead to a duplication of the source code: In the code you set member to 'a', in the test you check that member is 'a'. If you change the code, you have to change the tests.

It is slightly better with constructors that assign arguments to members, because you don't copy any hard coded values into your test. Still, the complexity is low, comparable to setters and getters.

For such trivial constructors I would try to benefit from the fact that constructors have to be called anyway to test any other method of the class. This can then be used to create test cases where the initial values after construction have an impact on the outcome of the test.

In your case, instead of writing a dedicated test where the constructor sets a score_threshold and then checking if that threshold was actually set, you could have a different test case: Call the constructor with a score_threshold, and then try to increment the score above that threshold. Here, the constructor is not just tested alone, it is part of a (slightly) bigger use case.

Obviously it is a different story if the constructor has more logic, for example scenarios where exceptions are raised due to invalid input. Then, dedicated tests for the constructor would make sense.

Dirk Herrmann
  • 5,550
  • 1
  • 21
  • 47