2013-08-12 30 views
1

我有我想測試代碼:如何使用assert_raises趕上SystemExit例外

from random import randint 

class End(object): 
      def __init__(self): 
      self.quips=['You dead', 'You broke everything you can','You turn you head off'] 

      def play(self): 
       print self.quips[randint(0, len(self.quips)-1)] 
       sys.exit(1) 

如何檢查是否退出或者是不使用accept_raises?

def test_End(): 
    end=End().play() 
    assert_raises(what should I put here) 

回答

0

可以在assertRaises趕上SystemExit例外:

with self.assertRaises(SystemExit): 
    End().play() 

或修補sys.exit通過mock

with patch.object(sys, 'exit') as mock_method: 
    End().play() 
    self.assertTrue(mock_method.called) 
+0

這僅適用於使用python unittest框架。它看起來不像OP在這裏使用。你可以從'nose.tools'中導入這個,雖然 – Greg

+0

@Greg yup,但是OP不會使用'nose' :) – alecxe

+0

lol wut:O這是很奇怪的標籤 – Greg

1

我喜歡@raises裝飾

from nose.tools import raises 

@raises(SystemExit) 
def test_End(): 
    end=End().play()