Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

spring test mock static method globally

in spring test, I know I can mock static method(usually static util methods: generate id, get value from Redis) using Mockito like:

try (MockedStatic) {
}

but having to do this in every test method is ugly and cumbersome, is there any way to do it all(i am ok to have a single mocked behavior)

I am thinking maybe a junit5 extension, or Mockito extension, this seems like a common problem, I wonder if anyone tries something with any success.

like image 314
danny Avatar asked Jul 28 '26 11:07

danny


1 Answers

try this

public class StaticClassTest {

    MockedStatic<YourStatic> mockedStatic;

    @Before
    public void setup() {
        mockedStatic = Mockito.mockStatic(YourStatic.class);

        // if you want the same behavior all along.
        mockedStatic.when(() -> YourStatic.doSomething(anyString())).thenReturn("TEST");
    }
    
    @Test
    public void test_static() {
        // write your test here
    }


    @After
    public void teardown() {
        mockedStatic.close();
    }
}
like image 58
Kai-Sheng Yang Avatar answered Jul 31 '26 00:07

Kai-Sheng Yang



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!