2012-11-18 4 views
0

터미널 대화 형 유틸리티를 테스트하기 위해 unittest을 사용하고 있습니다. 매우 비슷한 컨텍스트를 가진 두 개의 테스트 케이스가 있습니다. 하나는 올바른 출력을 테스트하고 다른 하나는 대화식 모드에서 사용자 명령을 올바르게 처리하는 테스트입니다. 그러나 두 경우 모두 sys.stdout을 모의 해 실제 출력을 억제합니다 (출력은 대화식 작업 과정에서도 수행됩니다). (심지어 더 많은 시간이있을 수 있습니다 지금은)여러 테스트 케이스에 공통된 컨텍스트를 설정하는 올바른 방법은 무엇입니까?

class StdoutOutputTestCase(unittest.TestCase): 
    """Tests whether the stuff is printed correctly.""" 

    def setUp(self): 
     self.patcher_stdout = mock.patch('sys.stdout', StringIO()) 
     self.patcher_stdout.start() 

    # Do testing 

    def tearDown(self): 
     self.patcher_stdout.stop() 


class UserInteractionTestCase(unittest.TestCase): 
    """Tests whether user input is handled correctly.""" 

    def setUp(self): 
     self.patcher_stdout = mock.patch('sys.stdout', StringIO()) 
     self.patcher_stdout.start() 

    # Do testing 

    def tearDown(self): 
     self.patcher_stdout.stop()  

는 내가 좋아하지 않는 것은 두 번 여기에 반복되는 상황에 맞는 설정입니다 :

는 다음과 같은 고려하십시오.

두 경우 모두 공통된 컨텍스트를 설정하는 좋은 방법이 있습니까? unittest.TestSuite 나를 도울 수 있습니까? 그렇다면 어떻게? 공통된 컨텍스트 설정에 대한 예제를 찾을 수 없었습니다.

나는 또한 setUp에서 두 가지 경우 모두 호출 될 수있는 함수 setup_common_context을 정의하려고 생각했지만 여전히 반복됩니다.

답변

1

기본 프로젝트에 공통 설정 코드를 입력하고 테스트 케이스를 파생 클래스에 넣는 것으로 프로젝트에서이 문제를 해결했습니다. 내 파생 된 클래스 setUp 및 tearDown 메서드는 수퍼 클래스 구현을 호출하고 해당 테스트 사례에 특정한 초기화 만 수행합니다. 또한 각 테스트 케이스에 여러 개의 테스트를 넣을 수 있으므로 모든 설정이 동일하면 의미가 있습니다.

class MyBaseTestCase(unittest.TestCase): 
    def setUp(self): 
     self.patcher_stdout = mock.patch('sys.stdout', StringIO()) 
     self.patcher_stdout.start() 

    # Do **nothing** 

    def tearDown(self): 
     self.patcher_stdout.stop() 

class StdoutOutputTestCase(MyBaseTestCase): 
    """Tests whether the stuff is printed correctly.""" 

    def setUp(self): 
     super(StdoutOutputTestCase, self).setUp() 

     # StdoutOutputTestCase specific set up code 

    # Do testing 

    def tearDown(self): 
     super(StdoutOutputTestCase, self).tearDown() 

     # StdoutOutputTestCase specific tear down code 

class UserInteractionTestCase(MyBaseTestCase): 
    # Same pattern as StdoutOutputTestCase 
관련 문제