问题描述
我试图在Python中使用unittest进行一个简单的测试,以查看一个类是否会为构造函数获取不合适的输入引发异常。该类看起来像这样: class SummaryFormula:
def __init __(self,summaryFormula):
self .atoms = {}
for re.finditer中的atom(([AZ] [az] {0,2})(\d *),summaryFormula):
symbol = atom.group (1)
count = atom.group(2)
如果pocet!=:
self.atoms [symbol] = int(count)
else :
self.atoms [symbol] = 1
我的测试如下:
class ConstructorTestCase(unittest.TestCase):
def testEmptyString(self):
self.assertRaises(TypeError,ukol1 .SummaryFormula(),testtest)
如果__name__ =='__main__':
unittest.main()
我想要的是测试失败,这意味着构造函数的不合适输入的异常不被处理。
相反,我收到一个错误: __ init __()只需要2个参数(1个给定)
。
我缺少什么?我应该指定什么是第二个参数?
此外,我应该使用什么类型的错误来处理异常,我的regexp不匹配的输入被传递给构造函数?
谢谢Tomas
参数,同时实例化对象
当您通过
ukol1。您应该将参数summaryFormula传递给它。 $ b $($)
b
ukol1.SummaryFormula(someSummaryFormula)
另外混淆是因为你的类名是SummaryFormula,你传递给 __ init __
的参数也是SummaryFormula
或者这应该是
self.assertRaises(TypeError,ukol1.SummaryFormula,testtest)
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")
这篇关于在Python中测试 - 如何在使用unittest测试中使用assertRaises?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!