2017-02-22 1 views
0

Java 함수의 테스트 케이스를 작성하려고합니다. 내 함수는 다음과 같은 유형의junit을 사용하여 함수를 테스트하는 동안 코드를 무시하십시오.

public static String parse33_05_x_Data(String message, Transaction transaction){ 
    String returnValue=""; 
    /** 
    *Some Java code which I actually want to test. 
    * 
    **/ 
    //Writing the transaction to the file. 
    FileManager.getInstance().WriteDataToFile(transaction); 
    return returnValue; 
} 

의 무언가 그러나 위의 코드에서 어떻게 든 무시하려면/ 라인 예외를주고있다으로 FileManager.getInstance().WriteDataToFile(transaction); 모의. 위의 함수 자체에 코드를 변경하지 않아도됩니다.

내 변경 사항은 내 Test class 내에서 발생해야합니다.

이렇게 할 수 있습니까?

미리 감사드립니다.

답변

0

fileManager 인스턴스를 param으로 두어야합니다. 그런 다음이 인스턴스를 조롱하는 것이 가능합니다. 또한

public static String parse33_05_x_Data(String message, FileManager fileManager, Transaction transaction){ 
    String returnValue=""; 
    /** 
    *Some Java code which I actually want to test. 
    * 
    **/ 
    // mock doesnt write 
    fileManager.WriteDataToFile(transaction); 
    return returnValue; 
} 

, 당신은 정적 메소드 FileManager.getInstance()을 조롱 PowerMockito를 사용할 수 있지만 내 생각에이 코드이기 때문에,이 권하고 싶지 않다 (당신은 당신이 방법을 변경하려면 그나마 쓰기) 냄새.

0

Mockito이라는 테스트 프레임 워크를 사용하여 매개 변수를 메소드에 조롱 할 수 있습니다. 이렇게하면 "아무 것도하지 않는"FileManager를 만들 수 있습니다. 당신은 다음과 같이 당신의 JUnit 테스트 케이스에서 개체를 조롱 Mockito를 사용할 수 있습니다

public static String parse33_05_x_Data(String message, Transaction transaction, FileManager fileManager){ 
    String returnValue=""; 
    /** 
    *Some Java code which I actually want to test. 
    * 
    **/ 
    //Writing the transaction to the file. 
    fileManager.WriteDataToFile(transaction); 
    return returnValue; 
} 

:

당신은 mockable

public static String parse33_05_x_Data(String message, Transaction transaction){ 
    String returnValue=""; 
    /** 
    *Some Java code which I actually want to test. 
    * 
    **/ 
    //Writing the transaction to the file. 
    FileManager.getInstance().WriteDataToFile(transaction); 
    return returnValue; 
} 

에 확인하기 위해 매개 변수에 파일 관리자를 리팩토링해야 을

@Test 
public void test1() { 
     // create mock 
     FileManager mockedFileManager = Mockito.mock(FileManager.class); 

     // define return value for method 
     when(mockedFileManager.WriteDataToFile()).thenReturn("something"); 


     // use mock in test.... 
     assertEquals(MyObj.parse33_05_x_Data("message") new Transaction(), mockedFileManager), "expected value"); 
} 
관련 문제