简体   繁体   English

如何测试从 Model 保存的方法?

[英]How can I do to test the method save from a Model?

I have this model:我有这个 model:

class Team(models.Model):
    user = models.CharField(max_length=250, default="default", null=True)


    def __str__(self):
        return self.user

And I would like to do a unittest for the save.我想为保存做一个单元测试。

I have that:我有这个:

class TeamModelTest(TestCase):
    @classmethod
    def setUpTestData(cls):
        Team.objects.create(user='Peter')

    def test_save(self):
        team = Team()
        team.user = 'Bruce'
        team.save()

But the problem is how can I do to test a function which return nothing?但问题是我该如何测试 function 什么都不返回?

Could you help me please?请问你能帮帮我吗?

Thank you very much !非常感谢 !

You could re-fetch the object from the DB and check that it is indeed updated.您可以从数据库中重新获取 object 并检查它是否确实已更新。

def test_save(self):
    // arrange
    team = Team()
    team.user = 'Bruce'

    // act
    team.save()

    // assert
    team_from_db = Team.objects.get(id=team.id)
    // assert that team_from_db.user == "Bruce"...

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

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