Static method mock sometimes calls native method

1,033 views
Skip to first unread message

twill...@sirlan.com

unread,
Oct 14, 2015, 5:44:17 AM10/14/15
to PowerMock
I Have been struggling testing my software and eventually found a strange behaviour of powermock.

here is the code failing tests:
import static org.junit.Assert.assertEquals;
import static org.powermock.api.mockito.PowerMockito.mockStatic;
import static org.powermock.api.mockito.PowerMockito.when;

import java.time.LocalDateTime;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

@RunWith(PowerMockRunner.class)
@PrepareForTest(LocalDateTime.class)
@PowerMockIgnore("javax.management.*")
public class StaticDummyPowermock {

   
@Test
   
public void doTest() {
        mockStatic
(LocalDateTime.class);
       
when(LocalDateTime.now()).thenReturn(null);
        assertEquals
(null, LocalDateTime.now());

        assertEquals
(null, new Object() {

           
public LocalDateTime run() {
               
return LocalDateTime.now();
           
}

       
}.run());
   
}
}

First assertion succeed but not the second one. Calling mocked method inside another class uses the real method instead of the stub. Therefore all my tests fails as LocalDateTime.now() is called outside of testClass.

I fixed my problem using another library. This code pass the tests

import static org.junit.Assert.assertEquals;

import java.time.LocalDateTime;

import mockit.Mock;
import mockit.MockUp;

import org.junit.Test;

public class StaticDummy {

   
@Test
   
public void doTest() {
       
new MockUp<LocalDateTime>() {
           
@Mock
           
LocalDateTime now() {
               
return null;
           
}
       
};
        assertEquals
(null, LocalDateTime.now());

        assertEquals
(null, new Object() {

           
public LocalDateTime run() {
               
return LocalDateTime.now();
           
}

       
}.run());
   
}
}

I Hope it helps !

Thomas. Willecomme.

Johan Haleby

unread,
Oct 14, 2015, 6:07:21 AM10/14/15
to powe...@googlegroups.com
Hi, 

It could be that LocalDateTime is system class and in that case you need to handle it specially.

Regards,
/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