Can static java.lang.Package.getPackage() be mocked?

301 views
Skip to first unread message

Michael Remijan

unread,
Nov 19, 2014, 9:10:52 AM11/19/14
to powe...@googlegroups.com
Greetings,

I've been attempting to mock the static method java.lang.Package.getPackage(String).  I've successfully used PowerMock to mock other static methods so I followed the same pattern to mock java.lang.Package.getPackage() and it didn't work.  I my unit test, the line PowerMock.verify(Package.class); fails to verify with a message saying "Package.getPackage(<any>): expected: 1, actual: 0".  So it's clear it's not getting mocked.  When I replace the call to Package.getPackage(String) with a class I specifically created, PackageGetter.getPackage(), this gets mocked successfully.  So is there something about Package being in the java.lang package which prevents it from being mocked?  NOTE: The Manifest object below is a method I created, not the JVM Manifest object.

@RunWith(PowerMockRunner.class)
@PrepareForTest(Package.class)
public class ManifestTest
{
     
@Before
   
public void before() {
       
MockitoAnnotations.initMocks(this);
   
}
     
   
@Test
   
public void getImplementationTitle()
   
{
       
// PowrMock, mock static
       
PowerMock.mockStatic(Package.class);
       
//        // Mock class which uses the static
//        Package p = Mockito.mock(Package.class);
//        Mockito.when(p.getImplementationTitle()).thenReturn("getImplementationTitle");
       
       
// Easymock, expect
       
EasyMock.expect(Package.getPackage(EasyMock.anyString())).andReturn(null);
       
       
// PowerMock, replay
       
PowerMock.replay(Package.class);
       
       
// Run test which uses static method
       
Manifest m = new Manifest(this.getClass());
       
String s = m.getImplementationTitle();
       
       
// PowerMock, verify
       
PowerMock.verify(Package.class);
       
       
// Assert
       
Assert.assertEquals("getImplementationTitle", s);
   
}

}



Johan Haleby

unread,
Nov 19, 2014, 10:03:29 AM11/19/14
to powe...@googlegroups.com
Hi,

It may work although I would advise strongly against doing it unless you really have to :) You must use this approach though.

/Johan

--
You received this message because you are subscribed to the Google Groups "PowerMock" group.
To unsubscribe from this group and stop receiving emails from it, send an email to powermock+...@googlegroups.com.
To post to this group, send email to powe...@googlegroups.com.
Visit this group at http://groups.google.com/group/powermock.
For more options, visit https://groups.google.com/d/optout.

Reply all
Reply to author
Forward
0 new messages