unittest测试简单python_在Python中测试 - 如何在使用unittest测试中使用assertRaises?...

I am trying to do a simple test in Python using unittest, to see if a class throws an exception if it gets an unsuitable input for the constructor. The class looks like this:

class SummaryFormula:

def __init__( self, summaryFormula):

self.atoms = {}

for atom in re.finditer( "([A-Z][a-z]{0,2})(\d*)", summaryFormula):

symbol = atom.group(1)

count = atom.group(2)

if pocet != "":

self.atoms[ symbol] = int(count)

else:

self.atoms[ symbol] = 1

My test is following:

class ConstructorTestCase(unittest.TestCase):

def testEmptyString(self):

self.assertRaises(TypeError, ukol1.SummaryFormula(), "testtest")

if __name__ == '__main__':

unittest.main()

All I want is the test to fail, meaning that the exception of unsuitable input for constructor is not handled.

Instead, I get an error: __init__() takes exactly 2 arguments (1 given).

What am I missing? What is the second argument I should specify?

Also, what type of Error should I use to handle exception that an input not matchable by my regexp was passed to the constructor?

Thank you, Tomas

解决方案

Thats because your class requires a parameter while instantiating the object

while you are passing

ukol1.SummaryFormula()

you should have been passing the parameter summaryFormula to it.

ukol1.SummaryFormula(someSummaryFormula)

Also the confusion is because your class name is SummaryFormula and the parameter that you pass to __init__ is also SummaryFormula

or should this be

self.assertRaises(TypeError, ukol1.SummaryFormula, "testtest")

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值