gre*_*reg 2 python testing unit-testing assert
我有关于unittest的问题.如何进行测试以查看是否存在异常?一个例子:
基准(3,32,2012)
如果我像这样调用类Datum,其中月份不在范围内(> 31),它就是一切正常,它会抛出异常并且没关系.但是如果Exception正常,我想做一个单元测试,如果正在捕获异常确定..?我做了一些测试,但这些只有True值,而且没关系.我不知道如何以这种方式进行测试..并在互联网上搜索..感谢您的回复.
import date,datetime
class Datum():
def __init__(self,day,month,year):
try:
d=int(day)
dvm=stevilodnivmesecu(month,year)
if (d>=1 and d<=dvm):
self.d=d
else:
raise Exception("Day out of moth range")
except:
raise ValueError("Day is not a number")
try:
m=int(month)
if m>=1 and m<=12:
self.m=m
else:
raise Exception("Month out of range")
except:
raise ValueError("Month is not a number")
try:
l=int(year)
if l>=1000 and l<=9999:
self.l=l
else:
raise Exception("Year is out of range")
except:
raise ValueError("Year is not a number")
def __repr__(self):
return repr(self.d)+"."+repr(self.m)+"."+repr(self.l)
def monthrange(month,year):
if month==2:
if jeprestopno(year)==True:
return 29
elif jeprestopno(year)==False:
return 28
elif month>=1 and month<=7:
if month%2!=0:
return 31
elif month>7 and month<=12:
if month%2==0:
return 31
elif month>=1 and month<=7:
if month%2==0:
return 30
elif month>7 and month<=12:
if month%2!=0:
return 30
else:
pass
def oneplusyear(year):
if year%4==0 or (year!=100 and year%4==0) or (year%400==0 and year%100==0):
return True
else:
return False
Run Code Online (Sandbox Code Playgroud)
使用
self.assertRaises(ValueError,Datum,3,32,2012)
Run Code Online (Sandbox Code Playgroud)
在你的unittest.TestCase测试中声称Datum(3,32,2012)提出了一个ValueError.
参考:
asserts您可以在TestCases中制作各种类型的文档.