Python的单元测试、类和方法

标签 python

有一个问题困扰我好几天了: 创建一个名为 BankAccount 的类

Create a constructor that takes in an integer and assigns this to a `balance` property.
Create a method called `deposit` that takes in cash deposit amount and updates the balance accordingly.
Create a method called `withdraw` that takes in cash withdrawal amount and updates the balance accordingly. if amount is greater than balance return `"invalid transaction"`
Create a subclass MinimumBalanceAccount of the BankAccount class

这是我的解决方案:

class BankAccount(object):
  def __init__(self, name, balance = 90):
    self.name = name
    self.balance = balance

  def deposit(self, amount):
    self.balance += amount
    return self.balance

  def withdraw(self, amount):
    if self.balance >= amount:
      self.balance -= amount
    else:
      return 'invalid transaction'

class MinimumBalanceAccount(BankAccount):
  def __init__(self, name, minimum):
    self.name = name
    self.minimum = minimum

这是我必须使用的单元测试:

import unittest
class AccountBalanceTestCases(unittest.TestCase):
  def setUp(self):
    self.my_account = BankAccount(90)

  def test_balance(self):
    self.assertEqual(self.my_account.balance, 90, msg='Account Balance Invalid')

  def test_deposit(self):
    self.my_account.deposit(90)
    self.assertEqual(self.my_account.balance, 180, msg='Deposit method inaccurate')

  def test_withdraw(self):
    self.my_account.withdraw(40)
    self.assertEqual(self.my_account.balance, 50, msg='Withdraw method inaccurate')

  def test_invalid_operation(self):
    self.assertEqual(self.my_account.withdraw(1000), "invalid transaction", msg='Invalid transaction')

  def test_sub_class(self):
    self.assertTrue(issubclass(MinimumBalanceAccount, BankAccount), msg='No true subclass of BankAccount')

但出于某种原因,当我尝试提交该结果时,我收到一条错误消息,指出我的解决方案未能通过所有测试。我在这里无能为力,我做错了什么?请帮忙

更新信息

这是我们看到的错误:

内部错误:runTests 中止:TestOutcomeEvent(handled=False, test=, result=, outcome='error', exc_info=(, TypeError('this constructor takes no arguments',), ), reason= None, expected=False, shortLabel=None, longLabel=None) 不是 JSON 可序列化的

最佳答案

您已经在您的类中接受了一个 name 参数,单元测试没有期望或通过该参数。删除它。

关于Python的单元测试、类和方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34634223/

相关文章:

python - 如何导入我在 Python 中创建的类并创建该类的实例?我收到一条错误消息,指出对象不可调用

python - 比较python中的字符串以查找错误

Python 登录 Voobly

python - windows上virtualenv下安装flask失败--【错误2】系统找不到指定的文件

python - 在Python中给定pandas数据框绘制多个堆叠条形图

python - 为什么Python中的本地函数更快以及如何证明?

python - Flask 导入错误 "cannot import name ' Flask'”

python - 为什么 set(None) 在 python 中无效

python - 将数据帧聚合到嵌套字典 (python)

python - 如何过滤掉有约会(外键关系)的个人资料?