2012-01-11 4 views
4

내 코드에 대한 JUnit 테스트를 작성하려고하지만 일부 메소드에서는 다른 메소드가 호출됩니다. 이 호출을 조롱하는 것이 가능한가?테스트중인 클래스에서 메소드 호출을 조롱 할 수 있습니까?

예.

s3FileWrite(File file, Status status) 
{ 
    S3 s3   = new S3(file.getName, s3Service) 
    String key = s3.getKey(); 
    String bucket = s3.getBucket(); 
    File tmp = new File("tmp/" + s3.getName()); 

    writeFile(key, bucket, tmp, status); //local method call I want to mock out 
}//awsFileWrite 

의 WriteFile 방법

내가 밖으로 조롱 할 것입니다 그리고 내가 테스트하고있는 클래스의 일부,하지만 난 그것을 조롱하는 방법을 모르겠어요. 테스트 할 클래스를 조롱 한 다음 내 기대에 대한 호출을 추가하는 것이 좋지만 여전히 메서드를 호출합니다.

아무도 나에게 여기에 할 일에 대한 조언을 해 줄 수 있습니까?

편집 :

내 JMock 코드는 다음과 같습니다

@Test 
public void testS3FileWrite() 
{  
    fileName  = context.mock(File.class); 
    s3Service = context.mock(FileDataAccessor.class); 
    s3   = context.mock(S3.class);   
    reportWriter = context.mock(ReportWriter.class); 

    try 
    { 
     context.checking(new Expectations(){{   
      oneOf(fileMetaData).getKey(); 
      will(returnValue("s3Key")); 

      oneOf(fileMetaData).getBucketName(); 
      will(returnValue("BucketName")); 

      oneOf(fileMetaData).getName(); 
      will(returnValue("TempFile")); 

      ((MethodClause) oneOf (any(File.class))).method("File").with(same("tmp/TempFile")); 

      oneOf(reportWriter).writeFile(with(same("s3Key")), 
            with(same("BucketName")), 
            with(any(File.class), 
            with(same(Status.OK))); 
     }});//Expectations 
    } 
    catch (Exception e) 
    { 
     ErrorStatus.debug("Exception in ReportTest.testS3FileWrite: " + e); 
    }//try-catch 

    ReportWriter test = new ReportWriter(status); 
    test.awsFileWrite(fileName, Status.OK); 
}//testAWSFileWrite 
+0

클래스를 조롱하고'writeFile()'의 예상 결과를 정의한 코드를 게시 할 수 있습니까? – jere

답변

4

PowerMock 당신에게 부분적으로 모의 수업을 할 수 있지만,이 JMock EasyMock에 아닙니다 설계되었습니다. 어쨌든 이것은 최선의 방법은 아닙니다. 아래 클래스에 덮어 쓰기의 fileWriter 필드 테스트 코드에서

// default implementation, can be replaced in tests 
FileWriter fileWriter = new FileWriter(); 

writeFile(key, bucket, tmp, status) { 
    fileWriter.write(key, bucket, tmp, status); 
}; 

:

새로운 클래스 FileWriter를 추가하고 대표 하나에, 테스트 대상 클래스에 다음, 그것에 writeFile 방법을 이동 테스트 (설정자 추가 또는 보호 된 필드 만들기) 모의 FileWriter.

+0

Cool :) 코드를 너무 많이 분리하지 않도록 내부 클래스로 추가했습니다. 건배 artbristol –

관련 문제