简体   繁体   中英

mocking final class with junit fail

I am trying to write junit using Powermock for below scenario. I have tried to write sample code instead of copying exact code which is not allowed to post here.

 class MainClass{
     First.getC().setStr("abc");
 }

 final class First{
   public static ClassC getC() {
        return c;
    }
 }

class ClassC{
  private String str;
  //getter/setter for str
 }

Its always failing. My junit is as follow:

@RunWith(SpringJUnit4ClassRunner.class)
public class MainClassTest {
  @Spy MainClass;

   @Mock
   private ClassC classc;

   @Before
   public void setup() {
     MockitoAnnotations.initMocks(this);
     PowerMockito.mockStatic(First.class);
   }
   @Test
   public void myTest(){
    when(First.getC()).thenReturn(classc);
    Mockito.doCallRealMethod().when(classc).setStr(Mockito.any(String.class)) 
 }
}

There is a detailed explanations about the steps required to mock static methods.

You are missing the crucial

Use the @PrepareForTest(ClassThatContainsStaticMethod.class) annotation at the class-level of the test case.

Beyond that: I think that it still will not work, because step one says:

Use the @RunWith(PowerMockRunner.class) annotation at the class-level of the test case.

Which would prevent you from using the Spring runner.

So, my suggestion here: forget about using static methods that require mocking in test cases. Keep in mind that static is an abnormality in good OOP anyway. So instead of "fixing" behavior in static methods - denote the functionality in an interface. Worst case you can still implement the interface in some class that has a static "singleton" instance which you then pass to the code that needs to use the interface.

Because then you can use plain Mockito to mock that interface and pass the mock around!

Long story short: you wrote hard to test code, forcing you to think about PowerMock - which would force you to abandon the Spring test runner - which would make your life 10 times harder. So change your code to be easy to test and forget about PowerMock.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM