简体   繁体   中英

Python Unit Test for Model Class

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.

我有一个def __init__(self): self.data = [1, 2]更改为self.data = [1, 2],通过魔术触摸,它导致了奇怪的错误,我希望我有一个type和值检查__init__()

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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