0
我處於編寫測試的過程中,必須缺少一些基本的東西,因爲看起來我創建的對象仍然是孤立的。在模型方法中未看到在TestCase中創建相關對象
我有Customers
,可以舉行一些Items.
測試裏面,屬於Customer
,我要總結的項目的價格爲客戶(使用客戶的方法)創建Items
(附價格)之後,但保持爲0.
實際的代碼更復雜,所以我簡化了細節,同時保持結構和邏輯相同。
帶有「生產」數據庫的版本工作正常,所以必須有關於我缺少測試及其數據庫的運行方式的信息。
### models.py
class Customer(models.Model):
name = models.CharField(max_length=20)
def compute_total(self):
total = 0
items = self.item_set.all()
for item in items:
total += item.price
return total
def __str__(self):
return self.name
class Item(models.Model):
customer = models.ForeignKey(Customer, on_delete=models.CASCADE)
name = models.CharField(max_length=20)
price = models.IntegerField()
def __str__(self):
return "%s %s (%s)" % (self.customer, self.name, self.price)
### tests.py
class CustomerTests(TestCase):
def test_add_two_items(self):
ken = Customer(name="Ken")
apple = Item(customer=ken, name="apple", price=10)
banana = Item(customer=ken, name="banana", price=2)
print(apple) # make sure apple is created, and it is.
self.assertEquals(ken.compute_total(), 12)
對於「生產」的版本,我手動添加喬和兩個水果如上面的管理,並與測試:
### views.py
def index(request):
joe = Customer.objects.get(name="Joe")
return HttpResponse(joe.compute_total())
這裏,一共是我所期望的,因此如何在測試中我能達到這種行爲嗎?
是的,我記得早些時候嘗試這種方法,並最終將測試數據保存到生產數據庫。現在我不記得那次出了什麼問題。所以我不確定這是否是正確的方法。事實證明,就像我剛纔測試的那樣,我將會發布一些與我自己的答案非常相似的東西。這看起來很麻煩,我希望能有一個緩和的解決方案。謝謝! –
如果你想避免保存到生產數據庫中,你應該使用'django.test.TestCase'而不是'unittest.TestCase'。更多信息[在這裏](https://docs.djangoproject.com/en/1.10/topics/testing/overview/)。 –
這是很好的信息要知道,再次感謝! –