Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/309.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/unit-testing/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
模型类的Python单元测试_Python_Unit Testing_Pytest - Fatal编程技术网

模型类的Python单元测试

模型类的Python单元测试,python,unit-testing,pytest,Python,Unit Testing,Pytest,假设我们有一个用于跟踪欺诈检查的模型类: class FraudCheck(object): def __init__(self, score_threshold): self.score = None self.transaction = None self.is_fraud = True self.score_threshold = score_threshold 我们应该为这个\uuuuu init\uuuu方法编

假设我们有一个用于跟踪欺诈检查的模型类:

class FraudCheck(object):

    def __init__(self, score_threshold):
        self.score = None
        self.transaction = None
        self.is_fraud = True
        self.score_threshold = score_threshold
我们应该为这个
\uuuuu init\uuuu
方法编写单元测试吗?类中还有其他方法

那么,我们是否应该编写类似以下内容的测试:

@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

我知道这个问题被标记为可能的重复,但是另一个问题是构造函数的值设置。在这个特殊的问题中,我们只设置了一个值,但还有三个其他变量也设置为默认值。我认为在重构过程中,如果变量混淆了,单元测试是合适的,但我希望其他人的意见

我有一个
def\uuuu init\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuself:self.data=[1,2]
更改为
self.data=[1,2],
通过神奇的触摸,它引起了奇怪的bug,我希望我有一个
类型
和值检查

将成员设置为硬编码值的简单构造函数的测试的问题在于,它们会导致源代码的重复:在代码中将成员设置为“a”,在测试中检查成员是否为“a”。如果更改代码,则必须更改测试

使用为成员分配参数的构造函数会稍微好一些,因为您不会将任何硬编码的值复制到测试中。尽管如此,复杂性还是很低,与setter和getter相当

对于这些微不足道的构造函数,我会尝试从这样一个事实中获益,即无论如何都必须调用构造函数来测试类的任何其他方法。然后,这可以用于创建测试用例,其中构造后的初始值会对测试结果产生影响

在您的情况下,您可以使用不同的测试用例,而不是编写一个专门的测试,其中构造函数设置一个
score\u阈值
,然后检查该阈值是否已实际设置,您可以使用一个
score\u阈值
调用构造函数,然后尝试将分数增加到该阈值以上。在这里,构造函数不仅仅是单独测试的,它是(稍微)更大用例的一部分

显然,如果构造函数具有更多逻辑,则情况就不同了,例如,由于无效输入而引发异常的场景。然后,为构造器进行专门的测试是有意义的。

可能重复的