<commit_before>[[test-method]]
= Testing Method Security

This section demonstrates how to use Spring Security's Test support to test method based security.
We first introduce a `MessageService` that requires the user to be authenticated in order to access it.

====
.Java
[source,java,role="primary"]
----
public class HelloMessageService implements MessageService {

	@PreAuthorize("authenticated")
	public String getMessage() {
		Authentication authentication = SecurityContextHolder.getContext()
			.getAuthentication();
		return "Hello " + authentication;
	}
}
----

.Kotlin
[source,kotlin,role="secondary"]
----
class HelloMessageService : MessageService {
    @PreAuthorize("authenticated")
    fun getMessage(): String {
        val authentication: Authentication = SecurityContextHolder.getContext().authentication
        return "Hello $authentication"
    }
}
----
====

The result of `getMessage` is a String saying "Hello" to the current Spring Security `Authentication`.
An example of the output is displayed below.

[source,text]
----
Hello org.springframework.security.authentication.UsernamePasswordAuthenticationToken@ca25360: Principal: org.springframework.security.core.userdetails.User@36ebcb: Username: user; Password: [<PASSWORD>]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Granted Authorities: ROLE_USER; Credentials: [PROTECTED]; Authenticated: true; Details: null; Granted Authorities: ROLE_USER
----

[[test-method-setup]]
== Security Test Setup

Before we can use Spring Security Test support, we must perform some setup. An example can be seen below:

====
.Java
[source,java,role="primary"]
----
@ExtendWith(SpringExtension.class) // <1>
@ContextConfiguration // <2>
public class WithMockUserTests {
----

.Kotlin
[source,kotlin,role="secondary"]
----
@ExtendWith(SpringExtension.class)
@ContextConfiguration
class WithMockUserTests {
----

This is a basic example of how to setup Spring Security Test. The highlights are:

<1> `@ExtendWith` instructs the spring-test module that it should create an `ApplicationContext`. For additional information refer to https://docs.spring.io/spring-framework/docs/current/reference/html/testing.html#testcontext-junit-jupiter-extension[Spring reference].
<2> `@ContextConfiguration` instructs the spring-test the configuration to use to create the `ApplicationContext`. Since no configuration is specified, the default configuration locations will be tried. This is no different than using the existing Spring Test support. For additional information, refer to the https://docs.spring.io/spring-framework/docs/4.0.x/spring-framework-reference/htmlsingle/#testcontext-ctx-management[Spring Reference]

NOTE: Spring Security hooks into Spring Test support using the `WithSecurityContextTestExecutionListener` which will ensure our tests are ran with the correct user.
It does this by populating the `SecurityContextHolder` prior to running our tests.
If you are using reactive method security, you will also need `ReactorContextTestExecutionListener` which populates `ReactiveSecurityContextHolder`.
After the test is done, it will clear out the `SecurityContextHolder`.
If you only need Spring Security related support, you can replace `@ContextConfiguration` with `@SecurityTestExecutionListeners`.

Remember we added the `@PreAuthorize` annotation to our `HelloMessageService` and so it requires an authenticated user to invoke it.
If we ran the following test, we would expect the following test will pass:

====
.Java
[source,java,role="primary"]
----
@Test(expected = AuthenticationCredentialsNotFoundException.class)
public void getMessageUnauthenticated() {
	messageService.getMessage();
}<commit_msg>Polish ExtendWith Docs<commit_after>[[test-method]]
= Testing Method Security

This section demonstrates how to use Spring Security's Test support to test method based security.
We first introduce a `MessageService` that requires the user to be authenticated in order to access it.

====
.Java
[source,java,role="primary"]
----
public class HelloMessageService implements MessageService {

	@PreAuthorize("authenticated")
	public String getMessage() {
		Authentication authentication = SecurityContextHolder.getContext()
			.getAuthentication();
		return "Hello " + authentication;
	}
}
----

.Kotlin
[source,kotlin,role="secondary"]
----
class HelloMessageService : MessageService {
    @PreAuthorize("authenticated")
    fun getMessage(): String {
        val authentication: Authentication = SecurityContextHolder.getContext().authentication
        return "Hello $authentication"
    }
}
----
====

The result of `getMessage` is a String saying "Hello" to the current Spring Security `Authentication`.
An example of the output is displayed below.

[source,text]
----
Hello org.springframework.security.authentication.UsernamePasswordAuthenticationToken@ca25360: Principal: org.springframework.security.core.userdetails.User@36ebcb: Username: user; Password: [<PASSWORD>]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Granted Authorities: ROLE_USER; Credentials: [PROTECTED]; Authenticated: true; Details: null; Granted Authorities: ROLE_USER
----

[[test-method-setup]]
== Security Test Setup

Before we can use Spring Security Test support, we must perform some setup. An example can be seen below:

====
.Java
[source,java,role="primary"]
----
@ExtendWith(SpringExtension.class) // <1>
@ContextConfiguration // <2>
public class WithMockUserTests {
----

.Kotlin
[source,kotlin,role="secondary"]
----
@ExtendWith(SpringExtension.class)
@ContextConfiguration
class WithMockUserTests {
----

This is a basic example of how to setup Spring Security Test. The highlights are:

<1> `@ExtendWith` instructs the spring-test module that it should create an `ApplicationContext`. For additional information, refer to the {spring-framework-reference-url}testing.html#testcontext-junit-jupiter-extension[Spring reference].
<2> `@ContextConfiguration` instructs the spring-test the configuration to use to create the `ApplicationContext`. Since no configuration is specified, the default configuration locations will be tried. This is no different than using the existing Spring Test support. For additional information, refer to the https://docs.spring.io/spring-framework/docs/4.0.x/spring-framework-reference/htmlsingle/#testcontext-ctx-management[Spring Reference]

NOTE: Spring Security hooks into Spring Test support using the `WithSecurityContextTestExecutionListener` which will ensure our tests are ran with the correct user.
It does this by populating the `SecurityContextHolder` prior to running our tests.
If you are using reactive method security, you will also need `ReactorContextTestExecutionListener` which populates `ReactiveSecurityContextHolder`.
After the test is done, it will clear out the `SecurityContextHolder`.
If you only need Spring Security related support, you can replace `@ContextConfiguration` with `@SecurityTestExecutionListeners`.

Remember we added the `@PreAuthorize` annotation to our `HelloMessageService` and so it requires an authenticated user to invoke it.
If we ran the following test, we would expect the following test will pass:

====
.Java
[source,java,role="primary"]
----
@Test(expected = AuthenticationCredentialsNotFoundException.class)
public void getMessageUnauthenticated() {
	messageService.getMessage();
}
{'fraction_non_alphanumeric': 0.09418729817007535, 'fraction_numerical': 0.0034983853606027986, 'mean_word_length': 5.57787610619469, 'pattern_counts': {'":': 0, '<': 13, '<?xml version=': 0, '>': 13, 'https://': 3, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5004764', 'n_tokens_mistral': 1894, 'n_tokens_neox': 1850, 'n_words': 709}