2017-08-04 57 views
1

问题:我写一个测试用例的方法从一个公共静态方法与下面的代码被称为:如何嘲笑“新FileOutputStram()”编写公共静态方法使用Powermockito

final File file = new File(filePath); 
    final OutputStream out = new FileOutputStream(file); 
    out.write(bytes); 
    out.close(); 

现在我需要模拟上面的调用。

我所写的: -

@Before 
public void setUp() throws Exception{ 
    File myFile = PowerMockito.mock(File.class); 
    FileOutputStream outStream = PowerMockito.mock(FileOutputStream.class); 

    PowerMockito.whenNew(File.class).withAnyArguments().thenReturn(myFile);   
    PowerMockito.whenNew(FileOutputStream.class).withAnyArguments().thenReturn(outStream); 

    doNothing().when(outStream).write(Matchers.any()); 
    doNothing().when(outStream).close(); 
} 

@Test 
public void testMethod(){ 
    PowerMockito.mockStatic(StaticClassUtil.class); 
    PowerMockito.when(StaticClassUtil.uploadFile(file.getBytes(), "dummy","dummy","dummy", null)).thenReturn("dummy");   
} 

在调试,我发现没有模拟对象在行:

final File file = new File(filePath); 

请建议在那里我得到错误的。

+0

很高兴阅读您的评论,这对我来说是一次学习体验,并且有一天我也努力推动自己也达到黄金照明徽章。:)你和我之间的 –

+2

:鉴于Illuminiator徽章是其中之一非常罕见的......它非常容易获得。您只需回答很多问题,并且每次在答案中获得第一个赞成票时,就可以编辑问题以改进它。换句话说:这个徽章只是关于许多答案和编辑。工作和纪律。还有其他徽章更难**。例如,有人问了100个有+1票或更多票的问题。虽然我问了+60个问题......我只有30个左右的upvotes。从这个意义上说:当你对徽章感兴趣... – GhostCat

+2

努力工作以达到“审核者”的特权...然后你可以获得大量的徽章...只是通过工作/纪律。 – GhostCat

回答

1

很有可能您错过了documentation中概述的步骤之一 - 可能您忘记将@PrepareForTest用于File.class和FileOutputStream.class。

但真正的答案是:你不一定直接调用在你的代码。您可以转而使用依赖注入框架为您执行此操作,或者只需将OutputStream传入到您的待测试方法中。因为那么你只有通过一个嘲弄的对象,你需要嘲笑那些讨厌的电话new()在空气中消失。你可以坚持使用老的Mockito而不是PowerMock(ito)。

+0

这是正确的,我当然错过了@PrepareForTest中的File.class和FileOutputStream.class。我以某种方式继续前进,并将在稍后在此处发现更新模式细节。 –