0

I got this test class:

@ExtendWith(SpringExtension.class)
@RunWith(PowerMockRunner.class)
@PrepareForTest({StaticClass.class})
public class ClassNameTest {

    @InjectMocks
    private ClassNameTest classNameTest;
    
    @Mock
    private DependencyClass dependencyClass;
    
    /* Other dependencies annotated with @Mock */

    @Test
    public void testFunction() {
    
        /* Mocking of the dependencies using Mockito.when() and friends. */
        
        PowerMockito.spy(StaticClass.class);
        Powermockito.when(StaticClass.function(Mockito.any()).thenReturn(/* The object function returns */);
        
        /* Rest of the test code. */
    
    }

}

The function I'm testing has somewhere inside a line that goes like this:

ReturnObject ro = StaticClass.function(parameter);

And obviously, what I want is to prevent StaticClass to be called and return a specially crafted object. Yeah, I know this static class is not the best approach, but that's outside the scope of my current problem.

My problem is that, when debugging the test code, it actually enters into StaticClass.function when calling Powermockito.when, and it fails there because somehow, enters with a null value.

All tutorials and guides I've seen says that this is basically what I need to do, so I'm completely lost here. Any ideas?

Neuromante
  • 531
  • 2
  • 12
  • 29
  • Check this out: https://stackoverflow.com/questions/10583202/powermockito-mock-single-static-method-and-return-object – M. Prokhorov Aug 27 '20 at 11:39

1 Answers1

2

Are you running your tests with JUnit 5 or 4? It's not clear, as you are using both, @ExtendWith (JUnit5 annotation) and @RunWith (JUnit4).

  • if you are using JUnit 5, PowerMock is, shortly speaking, not supported. @RunWith(PowerMockRunner.class) is ignored, @PrepareForTest({StaticClass.class}) has no effect, thus StaticClass is not initialized.
  • with JUnit 4 the test should work as expected, although @ExtendWith(SpringExtension.class) wouldn't work.
Mafor
  • 9,668
  • 2
  • 21
  • 36