2017-09-07 19 views
0

powerMock 또는 EasyMock 만 사용하여 다른 클래스에서 사용되는 클래스를 모의 해보려면이 두 프레임 워크 만 사용할 수 있습니다. Mockito를 사용할 수 있지만 코드베이스에는 easymock 및 powermock 라이브러리 만 포함되어 있으므로 두 클래스를 사용해야합니다. 프레임 워크 만.모의 테스트중인 클래스에서 사용되는 다른 클래스를 모의 하시겠습니까?

은 내가) (SecondClass.getVoidCall 방법을 모의 할 (내가 powerMock을 사용하고 있습니다)

public class ClassUnderTest { 

    public void getRecord() { 
     System.out.println("1: In getRecord \n"); 
     System.out.println("\n 3:"+SecondClass.getVoidCall()); 
     System.out.println("\n 4: In getRecord over \n"); 
    } 
} 

코드 아래에 있습니다.

public class ArpitSecondClass { 


    public static int getVoidCall() { 
     System.out.println("\n 2: In ArpitSecondClass getVoidCall for kv testing\n"); 
     return 10; 
    } 
} 

내 단위 테스트 코드는 기본적으로

@RunWith(PowerMockRunner.class) 
@PrepareForTest(TestArpit.class) 
public class UniteTestClass { 

    @Test 
    public void testMock() throws Exception { 
     SecondClass class2 = createMock(SecondClass.class); 
     expect(class2.getVoidCall()).andReturn(20).atLeastOnce(); 
     expectLastCall().anyTimes(); 

     ClassUnderTest a=new ClassUnderTest(); 
     a.getRecord(); 
     replayAll(); 
     PowerMock.verify(); 
} 

} 

내가

1: In getRecord 

2: In ArpitSecondClass getVoidCall for kv testing 

3:20 (Note:This should be overriden by the value I supplied in UnitTest) 

4: In getRecord over 

아래와 같이 출력하지만이 Unitest 코드를 얻고 출력을

2: In ArpitSecondClass getVoidCall for kv testing 
되고 싶은 것입니다

코드 흐름이 나 빠지지 않습니다. eyond expect (class2.getVoidCall()). andReturn (20) .atLeastOnce();

그리고 getRecord의 나머지 문장은 전혀 호출되지 않으므로 인쇄되지 않습니다.

여기에 뭔가가 있습니까?

+0

정적 방법을 사용하여 나쁜 연습 융통성이없고 재사용하기 어려운 코드. 그래서 당신에게 나쁜 디자인을 맡기고 * PowerMock *을 사용하는 대신'ArpitSecondClass'의 메소드에서'static' 키워드를 제거하고이 클래스의 인스턴스를 생성자 매개 변수로 테스트중인 클래스에 전달해야합니다. –

답변

3

SecondClass#getVoidCall() 방법 (public static int getVoidCall() {...})은 static 방법이므로 조롱은 조금 다릅니다.

교체 처음 두 행 :

@Test 
public void testMock() throws Exception { 
    SecondClass class2 = createMock(SecondClass.class); 
    expect(class2.getVoidCall()).andReturn(20).atLeastOnce(); 
아래 라인

(및 준비 클래스) :이 클래스의 종속성을 숨기고 당신을 수 있기 때문에

import static org.easymock.EasyMock.expect; 
import static org.powermock.api.easymock.PowerMock.mockStatic; 
... 

@RunWith(PowerMockRunner.class) 
@PrepareForTest({TestArpit.class, SecondClass.class})  // added SecondClass.class here 
public class UniteTestClass { 

    @Test 
    public void testMock() throws Exception { 
     mockStatic(SecondClass.class);         // changed this line 
     expect(SecondClass.getVoidCall()).andReturn(20).atLeastOnce(); // changed this line 
+0

쉽게 작업했습니다. 정말 고맙습니다. –