I am trying to understand Spring Security and i am stuck when implementing tests with @WebMvcTest.
I am using Spring Boot 4.0.3 with spring-boot-starter-webmvc, spring-boot-starter-webmvc-test, spring-boot-starter-security dependencies.
spring-boot-starter-security-test not included.
I have the below rest controller.
@RestController
public class DemoController {
private final DemoService demoService;
public DemoController(DemoService demoService) {
this.demoService = demoService;
}
@GetMapping("/hello")
public String hello() {
return demoService.hello();
}
}
Below is the test class.
@WebMvcTest(DemoController.class)
@AutoConfigureRestTestClient
class DemoControllerTest {
@Autowired
private RestTestClient restClient;
@MockitoBean
private DemoService demoService;
@BeforeEach
void beforeEachTest() {
Mockito.when(demoService.hello())
.thenReturn("Hello");
}
@Test
void test_hello() {
restClient.get()
.uri("/hello")
.exchange()
.expectStatus()
.isOk()
.expectBody(String.class)
.isEqualTo("Hello");
}
}
When i hit http://localhost:8080/hello without any credentials from Postman i get a 401 Unauthorized which makes sense.
When i run the test_hello test, it passes without any issue. I don't have any custom security configurations or @WithMockUser on the test.
When i include spring-boot-starter-security-test dependency in the pom.xml then the test fails with below message:
java.lang.AssertionError: Status expected:<200 OK> but was:<401 UNAUTHORIZED>
Expected :200 OK
Actual :401 UNAUTHORIZED
I don't understand how my test is passing without @WithMockUser.