Junit验证SpringRest失败

时间:2017-05-05 13:06:45

标签: java spring spring-boot junit spring-security

我在junit-test下面临着验证我的应用的问题。

我有一个CustomAuthenticationProvider

@Component
public class CustomAuthenticationProvider implements AuthenticationProvider {
    @Autowired
    private UserRepository userRepository;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
       //businness logic
       return auth;
    }
}

使用它的SecurityConfig

@Configuration
@EnableWebSecurity
@Import(CustomAuthenticationProvider.class)
public class SecurityConfig extends WebSecurityConfigurerAdapter  {

        @Autowired
        private CustomAuthenticationProvider customAuthenticationProvider;

        @Autowired
        public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
            auth.authenticationProvider(customAuthenticationProvider);
        }

        @Override
        protected void configure(HttpSecurity http) throws Exception {
          //some permission filters here
        }
    }

我的测试,应该调用Rest API并确保答案是肯定的。

@RunWith(SpringJUnit4ClassRunner.class)
@TestExecutionListeners({DependencyInjectionTestExecutionListener.class,
    TransactionalTestExecutionListener.class,
    DbUnitTestExecutionListener.class})
@SpringApplicationConfiguration(classes = {MyApplication.class},locations = {"/dbContext.xml"})
@TestPropertySource("/application.properties")
@WebIntegrationTest
public class SimpleTest {
    @Autowired
    protected WebApplicationContext webAppContext;

    @Autowired
    private CustomAuthenticationProvider customAuthenticationProvider;

    @Before
    public void setup() {
        RestAssuredMockMvc.webAppContextSetup(webAppContext);

        SecurityContext context = SecurityContextHolder.createEmptyContext();
        Authentication user = customAuthenticationProvider.authenticate(new UsernamePasswordAuthenticationToken("admin", "123"));
        context.setAuthentication(user);
        SecurityContextHolder.setContext(context);
     }


    @Test
    public void makeSureLoginIsOk() {
        given().when().get("/myurl").then().statusCode(200);
    }

}

嗯,测试总是失败,因为GET返回401而不是200。 任何人都可以帮忙,SecurityContext有什么问题?

1 个答案:

答案 0 :(得分:0)

终于找到了答案: 这篇文章How to Mock the security context in Spring MVC for testing很有帮助

@Before
public void setup() {
    RestAssuredMockMvc.webAppContextSetup(webAppContext);
    RestAssuredMockMvc.enableLoggingOfRequestAndResponseIfValidationFails();
    Authentication user = customAuthenticationProvider.authenticate(new UsernamePasswordAuthenticationToken("admin", "123"));
    RestAssuredMockMvc.authentication(user); //add this
    SecurityContextHolder.getContext().setAuthentication(user);
}


@Test
public void makeSureLoginIsOk() {
    RestAssuredMockMvc.get("/myurl").then().statusCode(200); //change given to RestAssured
}