簡體   English   中英

python單元測試用例中self.assertRaises未涵蓋的異常聲明

[英]Exception statement not covered by self.assertRaises in python unit test cases

這是我的功能:

def get_value(request, param):
  s = get_string(request, param)
  value = re.search('(\\d\\d\\d\\d)-(\\d\\d)-(\\d\\d)', s)
  if not value:
    print 'match not found!'  
    raise Exception('incorrect format: %s' % param)

測試功能:

def test_get_value(self):
    m = test_mocks.HttpRequestMock(REQUEST = {'start_date': '2011.07.31'})
    print '*************************'
    print 'date format changed'
    self.assertRaises(Exception, get_value, (m, 'start_date'))
    print '*********************

get_value不打印: 找不到匹配

你正確地將參數傳遞給assertRaises() ,你應該像這樣傳遞它們:

self.assertRaises(Exception, helpers.get_value, m, 'start_date')

這是一個適合我的完整測試用例。 第一次測試通過,第二次測試失敗。

import re
from unittest import TestCase

def get_value(s):
    value = re.search('(\\d\\d\\d\\d)-(\\d\\d)-(\\d\\d)', s)
    if not value:
        raise ValueError('incorrect format: %s' % s)

class TesterScratch(TestCase):
    # this one passes
    def test_get_value(self):
        s = '2011.07.31'
        self.assertRaises(ValueError, get_value, s)

    # this one fails, because the format is actually correct
    def test_get_value2(self):
        s = '2011-07-31'
        self.assertRaises(ValueError, get_value, s)

你的python版本似乎存在一些問題。 我猜你在2.6以下使用python。 嘗試將函數參數作為其他參數傳遞給函數,即不要將它們放在元組中。 試試這個。

self.assertRaises(Exception, helpers.get_value, m, 'start_date')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM