spring-security icon indicating copy to clipboard operation
spring-security copied to clipboard

Mutators throw NullPointerException when used with MockMvc setup

Open sjohnr opened this issue 3 years ago • 0 comments

When MockMvc is used to set up a WebTestClient, applying a mutator such as csrf() fails with a NullPointerException, but would ideally fail with a more meaningful error such as IllegalStateException to indicate it is not supported. The following Spring Boot tests illustrate the problem:

@WebMvcTest
public class WebTestClientTests {
	@Autowired
	private MockMvc mockMvc;

	@Test
	public void mockUserDetailsWhenMockMvcThenThrowsIllegalStateException() {
		UserDetails user = new User("user", "password", Collections.emptySet());
		assertThatIllegalStateException()
				.isThrownBy(() -> MockMvcWebTestClient.bindTo(mockMvc).apply(mockUser(user)).build());
	}

	@Test
	public void mockUserWhenMockMvcThenThrowsIllegalStateException() {
		assertThatIllegalStateException()
				.isThrownBy(() -> MockMvcWebTestClient.bindTo(mockMvc).apply(mockUser("user")).build());
	}

	@Test
	public void csrfWhenMockMvcThenThrowsIllegalStateException() {
		assertThatIllegalStateException()
				.isThrownBy(() -> MockMvcWebTestClient.bindTo(mockMvc).apply(csrf()).build());
	}

	@Test
	public void mockJwtWhenMockMvcThenThrowsIllegalStateException() {
		assertThatIllegalStateException()
				.isThrownBy(() -> MockMvcWebTestClient.bindTo(mockMvc).apply(mockJwt()).build());
	}

	@Test
	public void mockOpaqueTokenWhenMockMvcThenThrowsIllegalStateException() {
		assertThatIllegalStateException()
				.isThrownBy(() -> MockMvcWebTestClient.bindTo(mockMvc).apply(mockOpaqueToken()).build());
	}

	@Test
	public void mockOAuth2ClientWhenMockMvcThenThrowsIllegalStateException() {
		assertThatIllegalStateException()
				.isThrownBy(() -> MockMvcWebTestClient.bindTo(mockMvc).apply(mockOAuth2Client("test")).build());
	}

	@Test
	public void mockOAuth2LoginWhenMockMvcThenThrowsIllegalStateException() {
		assertThatIllegalStateException()
				.isThrownBy(() -> MockMvcWebTestClient.bindTo(mockMvc).apply(mockOAuth2Login()).build());
	}

	@Test
	public void mockOidcLoginWhenMockMvcThenThrowsIllegalStateException() {
		assertThatIllegalStateException()
				.isThrownBy(() -> MockMvcWebTestClient.bindTo(mockMvc).apply(mockOidcLogin()).build());
	}
}

Related gh-10841 gh-10900

sjohnr avatar Feb 22 '22 19:02 sjohnr