2014-09-29 1 views
0

싱글 톤 클래스의 단위 테스트를 작성한다면 어떻게 싱글 톤 클래스의 private 메소드를 조롱 할 수 있을까요? 내가 찾고 있어요 시나리오에 대한 샘플 코드는 다음과 같습니다 : -클래스가 PowerMock을 사용하여 테스트되는 경우 Singleton 클래스의 개인 메서드를 모의하는 방법?

Class Singleton { 
    private static Singleton instance = new Singleton(); 

    protected Singleton() {} 
    public Singleton synchronized getInstance() { return instance;} 

    public int method1(int a) { 
     int ret = method2(a); 
     return ret; 
    } 

    private int method2(int num) { return num + 1;} 
} 

가 어떻게 위의 예에서 방법 항목을 테스트하기 위해 방법 2를 조롱 할 수 있습니까?

+1

가 왜이 방법 항목을 테스트하기 위해 방법 2를 조롱해야합니까 모의? – clD

+0

저는 Unit Testing을 처음 사용합니다. 나는 method1을 테스트하기 위해 실제 method2에 대한 호출이 발생하지 않도록 더미 method2를 만들어야한다고 생각했습니다. 나의 접근 방식이 올바르지 않다면 친절하게도 단위 테스트 방법 1에 대해 어떻게해야합니까? – Siddharth

답변

1

method1을 테스트하려면 다른 방법처럼 테스트해야합니다. 이 경우 테스트 대상 객체 인 Singleton 클래스는 조롱되어서는 안됩니다.

보통 다음 설정 방법에 검사 (진찰)에서 클래스, 즉 테스트 개체를 만듭니다 예에서

@Test 
public void testMethod1() { 
    int testValue = 1;  
    int expectedResult = 2; 

    assertThat(testee.method1(testValue), equalTo(expectedResult)); 
} 

을 내가 정수 예를 들어 경계를 테스트하기 위해 JUnitParams 같은 뭔가 매개 변수화 테스트를 사용하는 것보다 당신이 SUT를 테스트 할 때 MAX_VALUE 등

@Test 
@Parameters(method = "method1Params") 
public void testMethod1(int testValue, int expectedResult) { 
    assertThat(testee.method1(testValue), equalTo(expectedResult)); 
} 

@Ignore 
private final Object[] method1Params() { 
    return new Object[] { 
     new Object { 1, 2 }, 
     new Object { -2, -1 } 
    }; 
} 

비웃음 주로 올바르게 작동하기 위해 다른 구성 요소 (협력자)에서 절연이 경우 싱글 톤에 사용됩니다. 이 경우에는 필요하지 않습니다.

당신이 사용할 수있는

public int method1(DependedOnComponent doc) { 
    int a = 1; 

    int ret = doc.method2(a); 

    return ret; 
} 

다음

@Test 
public void testMethod1() { 
    DependedOnComponent mockDOC = mock(DependedOnComponent.class); 

    // When method2() is called you control the value returned 
    when(mockDOC.method2(1)).thenReturn(2); 

    assertThat(testee.method1(mockDOC), equalTo(2)); 
} 
+0

답변 해 주셔서 감사합니다. 그래서, 메소드에 대한 테스트 (여기서는 method1)가 같은 클래스의 다른 private 메소드 (여기서는 method2)를 호출 할 수 있다고 생각합니까? 나는 "assertThat (testee.method1 (testValue), equalTo (expectedResult));"라고 말하고있다. method2에 대한 실제 호출도 수행합니다. – Siddharth

+0

예, 개인 방법을 조롱하는 것은 권장되지 않습니다. 또한'method2' 메소드를 호출하면 private 메소드의 동작을 테스트 할 수 있습니다. 대부분의 경우 개인적인 방법은 직접 테스트하지 않고 공개 API를 통해 테스트합니다. 개인적인 방법을 테스트하는 좋은 토론이 있습니다. http://stackoverflow.com/questions/105007/should-i-test-private-methods-or-only-public-ones – clD

+0

답변 해 주셔서 감사합니다. – Siddharth

관련 문제