SpringTestContext.java 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151
  1. /*
  2. * Copyright 2020-2022 the original author or authors.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * https://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. package sample.test;
  17. import java.io.Closeable;
  18. import java.util.ArrayList;
  19. import java.util.List;
  20. import jakarta.servlet.Filter;
  21. import jakarta.servlet.FilterChain;
  22. import jakarta.servlet.http.HttpServletRequest;
  23. import jakarta.servlet.http.HttpServletResponse;
  24. import org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor;
  25. import org.springframework.mock.web.MockServletConfig;
  26. import org.springframework.mock.web.MockServletContext;
  27. import org.springframework.security.config.BeanIds;
  28. import org.springframework.test.context.web.GenericXmlWebContextLoader;
  29. import org.springframework.test.web.servlet.MockMvc;
  30. import org.springframework.test.web.servlet.request.RequestPostProcessor;
  31. import org.springframework.test.web.servlet.setup.ConfigurableMockMvcBuilder;
  32. import org.springframework.test.web.servlet.setup.MockMvcBuilders;
  33. import org.springframework.test.web.servlet.setup.MockMvcConfigurer;
  34. import org.springframework.web.context.ConfigurableWebApplicationContext;
  35. import org.springframework.web.context.WebApplicationContext;
  36. import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
  37. import org.springframework.web.context.support.XmlWebApplicationContext;
  38. import org.springframework.web.filter.OncePerRequestFilter;
  39. import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity;
  40. /**
  41. * @author Rob Winch
  42. */
  43. public class SpringTestContext implements Closeable {
  44. private Object test;
  45. private ConfigurableWebApplicationContext context;
  46. private List<Filter> filters = new ArrayList<>();
  47. public SpringTestContext(Object test) {
  48. setTest(test);
  49. }
  50. public void setTest(Object test) {
  51. this.test = test;
  52. }
  53. @Override
  54. public void close() {
  55. try {
  56. this.context.close();
  57. }
  58. catch (Exception ex) {
  59. }
  60. }
  61. public SpringTestContext context(ConfigurableWebApplicationContext context) {
  62. this.context = context;
  63. return this;
  64. }
  65. public SpringTestContext register(Class<?>... classes) {
  66. AnnotationConfigWebApplicationContext applicationContext = new AnnotationConfigWebApplicationContext();
  67. applicationContext.register(classes);
  68. this.context = applicationContext;
  69. return this;
  70. }
  71. public SpringTestContext testConfigLocations(String... configLocations) {
  72. GenericXmlWebContextLoader loader = new GenericXmlWebContextLoader();
  73. String[] locations = loader.processLocations(this.test.getClass(), configLocations);
  74. return configLocations(locations);
  75. }
  76. public SpringTestContext configLocations(String... configLocations) {
  77. XmlWebApplicationContext context = new XmlWebApplicationContext();
  78. context.setConfigLocations(configLocations);
  79. this.context = context;
  80. return this;
  81. }
  82. public SpringTestContext mockMvcAfterSpringSecurityOk() {
  83. return addFilter(new OncePerRequestFilter() {
  84. @Override
  85. protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
  86. FilterChain filterChain) {
  87. response.setStatus(HttpServletResponse.SC_OK);
  88. }
  89. });
  90. }
  91. private SpringTestContext addFilter(Filter filter) {
  92. this.filters.add(filter);
  93. return this;
  94. }
  95. public ConfigurableWebApplicationContext getContext() {
  96. if (!this.context.isRunning()) {
  97. this.context.setServletContext(new MockServletContext());
  98. this.context.setServletConfig(new MockServletConfig());
  99. this.context.refresh();
  100. }
  101. return this.context;
  102. }
  103. public void autowire() {
  104. this.context.setServletContext(new MockServletContext());
  105. this.context.setServletConfig(new MockServletConfig());
  106. this.context.refresh();
  107. if (this.context.containsBean(BeanIds.SPRING_SECURITY_FILTER_CHAIN)) {
  108. // @formatter:off
  109. MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.context).
  110. apply(springSecurity())
  111. .apply(new AddFilter())
  112. .build();
  113. // @formatter:on
  114. this.context.getBeanFactory().registerResolvableDependency(MockMvc.class, mockMvc);
  115. }
  116. AutowiredAnnotationBeanPostProcessor bpp = new AutowiredAnnotationBeanPostProcessor();
  117. bpp.setBeanFactory(this.context.getBeanFactory());
  118. bpp.processInjection(this.test);
  119. }
  120. private class AddFilter implements MockMvcConfigurer {
  121. @Override
  122. public RequestPostProcessor beforeMockMvcCreated(ConfigurableMockMvcBuilder<?> builder,
  123. WebApplicationContext context) {
  124. builder.addFilters(SpringTestContext.this.filters.toArray(new Filter[0]));
  125. return null;
  126. }
  127. }
  128. }