代码之家  ›  专栏  ›  技术社区  ›  Cody Pritchard

Spring Boot-@Preauthorized在运行@DataJpaTest时被忽略

  •  0
  • Cody Pritchard  · 技术社区  · 5 年前

    我正在为一个应用程序编写JUnit测试,在尝试测试用 @Preauthorized .

    @WithMockUser(authorities = "some-authority") 对测试结果没有影响。它完成的时候好像 @预授权 注释从未存在过。

    @RunWith(SpringRunner.class)
    @DataJpaTest
    @Sql({"/db/all-schema.sql", "/db/all-data.sql"})
    public class MyControllerTest {
        @Autowired
        private MyRepository myRepository;
    
        private MockMvc mvc;
    
        @Before
        public void setUp() {
            MyService myService =  new MyService(this.myRepository);
            MyController myController = new MyController(myService);
    
            MockitoAnnotations.initMocks(this);
            this.mvc = MockMvcBuilders.standaloneSetup(myController).build();
        }
    
        @Test
        @WithAnonymousUser
        public void createObject_ShouldFailUnauthorized() throws Exception {
            JSONObject requestBody = new JSONObject();
            ...
    
            MockHttpServletResponse response = mvc.perform(post("/create")
                    .contentType(MediaType.APPLICATION_JSON)
                    .content(requestBody.toString())
            ).andReturn().getResponse();
    
            JSONObject jsonResponse = new JSONObject(response.getContentAsString());
            Assert.assertEquals(false, jsonResponse.getBoolean("success"));
            ...
        }
    }
    

    一些进一步的解释:

    • @DataJpaTest 这样我就可以在一次调用中调用API并测试控制器、服务和存储库方法。
    • @PreAuthorize("hasRole('my-role')")
    • 我在 spring-boot-starter-parent v2.2.5版

    当我运行测试时,无论我没有用户、匿名用户,还是正确的用户和正确的角色,测试总是通过,我无法让它执行预授权检查。

    一定有什么我遗漏了,但我在网上看到的所有例子都不包括用 .

    有人能提供更好的见解吗?

    0 回复  |  直到 5 年前