2012-03-29 6 views
1

저는 EasyMock 및 PowerMock에 익숙하지 않은데 아마도 아주 기본적인 것에 붙어 있습니다. PowerMock 및 EasyMock 방법 조롱 문제

다음

시험은 실패 난 내 테스트 코드는 다음

import java.io.File; 

public class FileOp() { 
private static FileOp instance = null; 
public string hostIp = ""; 

public static FileOp() { 
    if(null == instance) 
     instance = new FileOp(); 
} 

private FileOp() { 
    init(); 
} 

init() { 
    hostIp = "xxx.xxx.xxx.xxx"; 
} 

public boolean deleteFile(String fileName) { 
    File file = new File(fileName); 
    if(file.exists()) { 
     if(file.delete()) 
      return true; 
     else 
      return false; 
    } 
    else { 
     return false; 
    } 
} 

}

을 테스트하고자하는 내 코드 ...

import org.easymock.EasyMock; 
    import org.junit.Test; 
    import org.junit.runner.RunWith; 
    import org.powermock.api.easymock.PowerMock; 
    import org.powermock.core.classloader.annotations.PrepareForTest; 
    import org.powermock.modules.junit4.PowerMockRunner; 
    import org.powermock.reflect.Whitebox; 

    import java.io.File; 

    import static org.easymock.EasyMock.expect; 
    import static org.junit.Assert.assertFalse; 
    import static org.junit.Assert.assertTrue; 

    @RunWith(PowerMockRunner.class) 
    @PrepareForTest(FileOp.class) 
    public class FileOp_JTest 
    { 

@Test 
@PrepareForTest(File.class) 
public void deleteFile_Success(){ 
    try { 
     final String path = "samplePath"; 

     //Prepare 
     File fileMock = EasyMock.createMock(File.class); 

     //Setup 
     PowerMock.expectNew(File.class, path).andReturn(fileMock); 
     expect(fileMock.exists()).andReturn(true); 
     expect(fileMock.delete()).andReturn(true); 

     PowerMock.replayAll(fileMock); 

     //Act 
     FileOp fileOp = Whitebox.invokeConstructor(FileOp.class); 
     assertTrue(fileOp.deleteFile(path)); 

     //Verify 
     PowerMock.verifyAll(); 
    } 
    catch (Exception e) { 
     e.printStackTrace(); 
     assertFalse(true); 
    } 
} 

}이다 때문에 assertTrue (fileOp.deleteFile (path));

file.exists()를 호출 할 때 deleteFile ("samplePath")까지 추적하고 false를 반환합니다. 그러나, 나는 사실을 반환 file.exists() 조롱있다.

+0

문제를 해결할 수있었습니다. 테스트가 통과되면 PrepareForTest에 대한 클래스 수준에서 File 및 FileOp 클래스를 모두 추가합니다. 클래스 수준에서 @PrepareForTest를 제거하고 @PrepareForTest ({File.class, FileOp.class}) 테스트를 실행하면 패스. 여기서 볼 수 있듯이 @PrepareForTest (File.class)는 클래스 수준에, PrepareForTest (FileOp.class)는 메서드 수준에 배치했습니다. 왜 이런 일이 발생합니까? – maverick

답변

0

테스트에 사용중인 파일이 조롱을받지 않았습니다. fileMock을 가지고 있지만 테스트 중에는 사용되지 않습니다. 당신이 테스트 방법은 다음 줄에 자신의 새로운 File 객체를 인스턴스화 : 당신의 DeleteFile을 방법 대신 문자열의 File 객체를 취할 것입니다 당신이 거기 당신의 모의 객체를 주입 모든 통화가 올바른지 확인 할 수

File file = new File(fileName); 

합니다.