Home > Software engineering >  spring test mock static method globally
spring test mock static method globally

Time:04-19

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.

CodePudding user response:

try this

public class StaticClassTest {

    MockedStatic<YourStatic> mockedStatic;

    @Before
    public void setup() {
        mockedStatic = Mockito.mockStatic(YourStatic.class);
    }
    
    @Test
    public void test_static() {
        // write your test here
    }


    @After
    public void teardown() {
        mockedStatic.close();
    }
}

CodePudding user response:

You are also able to mock in a @BeforeEach method instead in all the tests seperately.

public class Test {
    private MockedStatic<Files> filesMock;

    @BeforeEach
    public void init() {
        filesMock = org.mockito.Mockito.mockStatic(Files.class);
        filesMock.when(() -> Files.copy(any(Path.class), any(OutputStream.class))).thenReturn(1L);
    }

    @AfterEach
    public void teardown() {
        filesMock.close();
    }
    
    @Test
    void test() {
       // uses mock
    }
}
  • Related