【问题标题】:JUnit Test with Spring Security使用 Spring Security 进行 JUnit 测试
【发布时间】:2017-08-25 06:16:32
【问题描述】:

我想测试一下,我无权这样做。 这是我的代码:

/* imports */

@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)
@WebAppConfiguration
public class AuthenticationTest {

private UsernamePasswordAuthenticationToken authentication;

@Autowired
private AuthenticationManager authManager;

    public void before() throws Exception {
        this.authentication = new UsernamePasswordAuthenticationToken("username", "password");
        SecurityContextHolder.getContext().setAuthentication(manager.authenticate(authentication));

    }

    @Test(expected = AccessDeniedException.class)
    public void postExperience() throws Exception {
        ExperienceEntity experience = new ExperienceEntity();
        experience.setExperience("Test");
        experience.setExperienceEng("Test");

        mockMvc.perform(
                    post(URL_EXPERIENCES).principal(authentication).content(json(experience)).contentType(CONTENT_TYPE))
                    .andExpect(status().isForbidden());
        }

错误日志:

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.security.access.AccessDeniedException: Access is denied

我不明白为什么这个测试不起作用。我收到了这些错误,这是我预期的。

【问题讨论】:

    标签: java spring junit spring-security


    【解决方案1】:

    看起来是异常类型的问题。您期待AccessDeniedException,但将其包裹在NestedServletException 中。为了让您的测试成功,您可以这样做:

    try {
        mockMvc.perform(post(URL_EXPERIENCES).principal(authentication)
            .content(json(experience)).contentType(CONTENT_TYPE))
            .andExpect(status().isForbidden());
        Assert.fail();
    } catch (Exception e) {
        Assert.assertTrue(e.getCause() instanceof AccessDeniedException);
    }
    

    并从您的 @Test 注释中删除 expected 属性。 希望对您有所帮助!

    【讨论】:

      【解决方案2】:

      您可以使用expectCause 捕捉NestedServletException

      import org.junit.Rule;
      import org.junit.rules.ExpectedException;
      
      public class AuthenticationIntegrationTest {
      
          @Rule public ExpectedException thrown = ExpectedException.none();
      
          @Test
          public void postExperience() throws Exception {
              // given
              ...
      
              // then
              thrown.expectCause(is(instanceOf(AccessDeniedException.class)));
      
              // or thrown.expectCause(isA(AccessDeniedException.class));
      
              // when
              mockMvc.perform(post(URL_EXPERIENCES).principal(authentication).content(json(experience))
                      .contentType(CONTENT_TYPE))
                      .andExpect(status().isForbidden());
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-09-26
        • 2015-08-12
        • 1970-01-01
        • 2021-12-08
        • 2017-10-21
        相关资源
        最近更新 更多