'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.



Solution 1:[1]

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();
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1