Django模拟查询集

时间:2018-12-22 14:32:14

标签: python django unit-testing

播放器类:

class Players:
  def __init__(self):
      self.players = PlayerModel.objects.all()

  def count(self):
      return len(self.players)

测试:

    def setUp(self):
      self.players = Players()

@patch('riskgame.entities.Players.count', return_value=9, create=True)
def test_count(self):
    number = self.players.count()
    self.assertEqual(number, 9)

此测试抛出:

Failed: Database access not allowed, use the "django_db" mark, or the "db" or "transactional_db" fixtures to enable it.

但是为什么需要这个测试数据库?似乎Players.count()上的@patch无法正常工作。有没有更好的解决方案来使其更具可测试性?

1 个答案:

答案 0 :(得分:0)

使用

覆盖房地产参与者来解决此问题

def setUp(self): self.players = []