1

Spring プロジェクトに単体テストを追加しようとしています(ところで、統合テストは正常に動作します) が、コントローラーがインターフェースを実装する場合に (JSR-250 アノテーションを使用して)Controllers構成を追加すると、非常に奇妙な動作が発生します (@EnableGlobalMethodSecurityどのインターフェースでも)ControllerSpringアプリケーションコンテキストには「リクエストハンドラー」として含まれていません(メソッドで確認しorg.springframework.web.servlet.handler.AbstractHandlerMethodMapping.processCandidateBean(String beanName)ました:)、つまり、コントローラーで定義されたリクエストマッピング(@PostMapping、...)は潜在的な場所として登録されていませんが、インターフェイスを削除すると、コントローラとパスが問題なく見つかります。

これは、単純なインターフェイスを備えた私のコントローラー (簡略化)MyInterfaceです。

@RestController
@RequestMapping(path = "/api/customer")
@RolesAllowed({Role.Const.ADMIN})
public class CustomerController implements MyInterface {    
    @Override // The only method in MyInterface 
    public void myMethod(Object param) throws QOException {
        System.out.println("Hello");
    }    
    @PostMapping(path = {"/", ""})
    public Customer create(@RequestBody Customer data) throws QOException {
        return customerService.create(data);
    }
}

そして、これは Test クラスです (構成クラスを削除すると、@EnableGlobalMethodSecurityすべて正常に動作します):

@RunWith(SpringRunner.class)
@WebMvcTest(controllers = CustomerController.class)
@Import({ CustomerController.class, TestAuthConfiguration.class, TestAuthConfiguration2.class})  //, TestAuthConfiguration.class })
@ActiveProfiles({"test", "unittest"})
@WithMockUser(username = "test", authorities = { Role.Const.ADMIN })
class CustomerControllerTest {
    private static final Logger LOG = LogManager.getLogger(CustomerControllerTest.class);
    @EnableWebSecurity
    protected static class TestAuthConfiguration extends WebSecurityConfigurerAdapter {
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            LOG.info("configure(HttpSecurity http) ");
            http.csrf().disable().authorizeRequests().filterSecurityInterceptorOncePerRequest(true)
                    .antMatchers("/api/session/**").permitAll() //
                    .antMatchers("/api/**").authenticated() //
                    .anyRequest().permitAll().and() //
                    .addFilterBefore(new OncePerRequestFilter() {
                        @Override
                        protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
                                FilterChain filterChain) throws ServletException, IOException {
                            Authentication auth = SecurityContextHolder.getContext().getAuthentication();
                            if (auth != null) {
                                LOG.info("User authenticated: {}, roles: {}", auth.getName(), auth.getAuthorities());
                            }
                            filterChain.doFilter(request, response);
                        }
                    }, BasicAuthenticationFilter.class).sessionManagement()
                    .sessionCreationPolicy(SessionCreationPolicy.STATELESS);
        }

    }

    @EnableGlobalMethodSecurity(jsr250Enabled = true, securedEnabled = false)
    protected static class TestAuthConfiguration2 extends GlobalMethodSecurityConfiguration {
        @Bean
        public GrantedAuthorityDefaults grantedAuthorityDefaults() {
            return new GrantedAuthorityDefaults(""); // Remove the ROLE_ prefix
        }
    }

    @Autowired
    MockMvc mockMvc;

    @Test
    void testCreate() throws Exception {
        Customer bean = new Customer();
        bean.setName("Test company");           
        when(customerServiceMock.create(bean)).thenReturn(bean);
        mockMvc.perform(post("/api/customer") 
        .content(JsonUtils.toJSON(bean)).contentType(MediaType.APPLICATION_JSON))
                .andExpect(status().isOk())
                .andExpect(MockMvcResultMatchers.content().contentType(MediaType.APPLICATION_JSON))
                .andExpect(MockMvcResultMatchers.jsonPath("$.name").value("Test company"));
    }
}

何が起こっているのかわかりません。注釈 JSR-250 (@RollesAllowed) に基づいたセキュリティを備えたコントローラーでの単体テストの例を見つけようとしましたが、有用なものは何も見つかりませんでした。 me) バグですが、よくわからないので、どんな助けでも大歓迎です。

ライブラリのバージョン:

  • スプリング ブート バージョン: 2.2.2
  • スプリングコア: 5.2.1
  • モッキートコア: 3.1.0
4

1 に答える 1