How can I mock MyClass.class.getClassLoader ()?

Is it possible to ridicule (or at least suppress) a challenge like

MyClass.class.getClassLoader().getResourceAsStream("file.txt")

      

with help PowerMock

?

+3


source to share


1 answer


One solution (I think this was what Bayou.io meant in one of the comments) would be to abstract the resource distraction, as in:

public interface ResourceRetriever{
    public InputStream getResource(String location);
}

public class ClassloaderResourceRetriever implements ResourceRetriever{
    @Override
    public InputStream getResource(String location){
        this.getClass().getClassLoader().getResourceAsStream();
    }
}

public class MyClassThatNeedsSomeResources {
    private final ResourceRetriever resourceRetriever;

    public MyClassThatNeedsSomeResource (ResourceRetriever resourceRetriever){
        this.resourceRetriever = resourceRetriever;
    }

    public void myMethodThatNeedsSomeResource(){
        InputStream resource = resourceRetriever.getResource("foo");
        // use your newly retrieved resource
    }
}

      

Thanks to this, you can easily make fun of the retriever, as in



...
@Test
public void resourceShouldBeRetrieved() {
    // given
    ResourceRetriever r = Mockito.mock(ResourceRetriever.class);
    ByteArrayInputStream fakeResource = new ByteArrayInputStream("foobar".getBytes());
    when(r.getResource("foo").thenReturn(fakeResource);

    MyClassThatNeedsSomeResources c = new MyClassThatNeedsSomeResources(r);


    // when
    c.myMethodThatNeedsSomeResource();

    // then
    verify(r).getResource("foo");
}

      

This abstraction will also make your code more reusable, as you can easily implement a ResourceRetriever that works with Spring Resources , URLs , Files, or other variations.

0


source







All Articles