encoding - mock java.nio.file.Paths.get do nothing but throw InvalidPathException -


i have 2 line of code:

file file = new file("report_はな.html"); path path = paths.get(file.getcanonicalpath()); 

is there anyway can mock static method:

paths.get(file.getcanonicalpath()); 

and throw exception invalidpathexception?

i tried powermockito, seems not working

powermockito.mockstatic(paths.class); powermockito.doreturn(null).dothrow(new invalidpathexception("","")).when(paths.class); 

the whole idea trying reproduce bug under english mac, mac default encoding setting us-ascii, path path = paths.get("report_はな.html"); throw invalidpathexception.

as documented here, have jump through hoops mock "system" classes, i.e. classes loaded system classloader.

specifically, whereas in normal powermock test @preparefortest() annotation identifies class static methods want mock, in "system" powermock test annotation needs identify class calls static methods (usually class under test).

for instance, have following class:

public class foo {     public static path doget(file f) throws ioexception {         try {             return paths.get(f.getcanonicalpath());         } catch (invalidpathexception e) {             return null;         }     } } 

we want test class in fact return null if paths.get() throws invalidpathexception. test this, write:

@runwith(powermockrunner.class)  // <- important! @preparefortest(foo.class)       // <- note: foo.class, not paths.class public class footest {     @test     public void dogetreturnsnullforinvalidpathexception() throws ioexception {         // enable static mocking on paths         powermockito.mockstatic(paths.class);          // make paths.get() throw ipe arguments         mockito.when(paths.get(any(string.class)))           .thenthrow(new invalidpathexception("", ""));          // assert method invoking paths.get() returns null         assertthat(foo.doget(new file("foo"))).isnull();     } } 

note: wrote paths.get(any(string.class)) mock more specific if need be, e.g. paths.get("foo")) or paths.get(new file("report_はな.html").getcanonicalpath()).


Comments

Popular posts from this blog

google chrome - Developer tools - How to inspect the elements which are added momentarily (by JQuery)? -

angularjs - Showing an empty as first option in select tag -

php - Cloud9 cloud IDE and CakePHP -