Spring security test practice

introduction

The security module of the test question management system uses spring security, and the code is transplanted from the original Hua soft warehouse. In the process of transplantation, it is found that the original test is not well written, so the security module test is reconstructed in the new system.

Spring testing

Add the @ springboottest annotation, which means that this is a unit test based on springboot.

Springboot provides a variety of testing methods in the official guide.

@The webenvironment attribute in the springboottest annotation can configure the test environment, which defaults to the mock environment.

/**
 * The type of web environment to create when applicable. Defaults to
 * {@link WebEnvironment#MOCK}.
 * @return the type of web environment
 */
WebEnvironment webEnvironment() default WebEnvironment.MOCK;

Simulated environment test

After spring security is enabled, the API test in the unit test will be intercepted by the spring security filter, so the user login operation is required before the test.

Before, we used a cumbersome method to write a @ before, log in in @ before, and then execute the test method.

Recently, after reading the spring security test document, I finally found a very simple method to simulate login, @ withmockuser.

test method with mock user - spring security test

Introduce spring security test dependency:

<!-- Spring Security Test -->
<dependency>
  <groupId>org.springframework.security</groupId>
  <artifactId>spring-security-test</artifactId>
  <scope>test</scope>
</dependency>

The example code is as follows:

@SpringBootTest
@RunWith(SpringRunner.class)
@AutoConfiguremockmvc
@WithMockUser(username = "admin",password = "admin")
public class ControllerTest {

  @Autowired
  protected mockmvc mockmvc;

  @Test
  void contextLoads() {
  }
}

Note: @ runwith (springrunner. Class) indicates that the current test uses org springframework. test. context. junit4. JUnit 5 is fully enabled in the latest spring boot version, and JUnit 4.0 is not recommended Spring runner is not used in production projects because it has not been internally studied and tested.

Real environment test

In order to reduce the cost of learning and communication, previously, all tests were specified in the mock environment, using mockmvc for API testing.

Although the mock environment can solve most problems and can be tested directly without starting the server, in some scenarios, HTTP service and request testing in the real environment is still required.

After spring security is enabled, mockmvc is a direct test controller, not a real HTTP server. Mockhttpsession is used in mock environment, which is not a standard session implementation and does not add support for cookie. Therefore, when testing the security module, cookie and other authentication information cannot be tested like a browser.

spring mockmvc doesn't contain cookies - stackoverflow

There is no solution on stackoverflow. It is recommended to use testresttemplate + real server environment for unit testing.

Configure the webenvironment as springboottest WebEnvironment. RANDOM_ Port means that the current test runs in a real web environment with a random port.

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class AuthControllerTest {
  @Autowired
  private TestRestTemplate restTemplate;
}

During the test, testresttemplate is used to send network requests to truly simulate the web server environment.

The example code is as follows:

logger.debug("3: 测试用户名密码正确");
username = RIGHT_USERNAME;
password = RIGHT_PASSWORD;
response = this.restTemplate
    .withBasicAuth(username,password)
    .getForEntity(CONfig_LOGIN,Void.class);

logger.debug("断言: 状态码为200");
assertThat(response.getStatusCode().value()).isEqualTo(HttpStatus.OK.value());

logger.debug("获取 response 的 Set-Cookie 信息,并断言");
String setCookie = response.getHeaders().getFirst(HttpHeaders.SET_COOKIE);
assertThat(setCookie).isNotNull();

summary

The two have their own advantages. Before, we always used the simple and convenient mock environment for testing, but one day, when we found that the mockhttpsession under the mock environment test could not meet the requirements, we began to explore other test schemes.

The above is the whole content of this article. I hope it will help you in your study, and I hope you will support us a lot.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>