References:

To test your controllers without disabling CSRF, you can do the following:

1. First import statically the package bellow:

import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.*;

2. Then in your MockMvc request:

with(csrf())

3. And last:

this.mockMvc
            .perform(post("/users").with(csrf())
                    .content(objectMapper.writeValueAsString(createUserDto))
                    .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE))
            .andExpect(status().isCreated());

The recomendation from Spring, says the following:

When should you use CSRF protection? Our recommendation is to use CSRF protection for any request that could be processed by a browser by normal users. If you are only creating a service that is used by non-browser clients, you will likely want to disable CSRF protection.