2017-06-21 106 views
3

所以我想在一个有静态方法的方法上使用Mockito。原因是我无法使用PowerMock,因此我使用非静态方法封装了该方法。如何正确使用Mockito静态方法包装在非静态方法中?

public class WrapperUtil { 

    public String getURLContent(String path) throws IOException{ 
     URL url = new URL(path); 
     return IOUtils.toString(url); 
    } 
} 

现在我用两种不同的方式测试了WrapperUtil类。一个测试工作,但没有提供任何WrapperUtil类的覆盖,另一个是抛出一个空指针异常相关的静态方法。

这是一个工程,但没有提供任何报道。

@RunWith(MockitoJUnitRunner.class) 
public class WrapperUtilTest { 

    @InjectMocks 
    WrapperUtil ioutils; 


    @Before 
    public void setUp() throws Exception { 

     ioutils = new WrapperUtil(); 
    } 

    @Test 
    public void testGetUrlContent() throws IOException { 

     WrapperUtil ioutilsSpy = Mockito.spy(ioutils); 
     Mockito.doReturn("test").when(ioutilsSpy).getURLContent(Mockito.anyString()); 
     assertTrue(ioutils2.getURLContent("test").contains("test")); 

    } 

} 

这是一个不工作:

@RunWith(MockitoJUnitRunner.class) 
public class WrapperUtilTest { 

    @InjectMocks 
    WrapperUtil ioutils; 


    @Before 
    public void setUp() throws Exception { 

     ioutils = new WrapperUtil(); 
    } 

    @Test 
    public void testGetUrlContent() throws IOException { 

     WrapperUtil ioutilsSpy = Mockito.spy(ioutils); 
     Mockito.when(ioutilsSpy).getURLContent(Mockito.anyString()).thenReturn("test"); 
     assertTrue(ioutils2.getURLContent("test").contains("test")); 

    } 

} 

我怎样才能使这项工作,并实现代码覆盖,而不使用PowerMockito?非常感谢你的帮助。

+0

无关:您的代码示例中出现拼写错误。你声明'ioutils' - 但是你使用'ioutils2'。 – GhostCat

+0

除了那个不清楚的地方:很好的第一个问题。我特别喜欢你的态度,以达到高品质(尽管我的答案在这里有不同的方向)**和**你的理解,你想避免PowerMock。我希望我能再次为你赢得三次胜利! – GhostCat

+0

最后,再次无关:假设您正在使用Apache IOUtils.toString() - 请注意,此方法*弃用*,您应该使用取代编码的方法! – GhostCat

回答

1

我的两个百分之这里:

  • 我甚至会走一步,定义一个接口表示功能
  • 在另一方面,我也不会去“落水”测试包装实施

要点是:只有一点点胶水代码在这里。如果您能够测试此代码来验证此胶水代码的作品 - 那么你很好。

换句话说:避免挂上100%的覆盖率!覆盖范围是工具,设计为帮助您实现代码质量。

100%覆盖范围不是导致“100%代码质量”!

通过尝试“始终做正确的事情”来实现代码质量。

在这里,“正确的事情”是不争取100%的覆盖面。

因为我猜你不会在没有转向PowerMock(ito)的情况下达到这个目标。而且,避免PowerMock(ito)本身就是一件好事 - 我的建议是:简单地接受你无法达到100%的覆盖率。

如果有的话,我会花我的时间试图排除这个类从覆盖运行。