Java 使用Springboot的单元测试基础

Java 使用Springboot的单元测试基础,java,spring,unit-testing,spring-boot,basic-authentication,Java,Spring,Unit Testing,Spring Boot,Basic Authentication,我已经在我的SpringBoot应用程序中实现了BasicAuth,以验证几个URL。有点像: 配置类 @EnableWebSecurity @Configuration public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Value("${auth.authenticated}") private String[] allAuthenticated

我已经在我的
SpringBoot
应用程序中实现了
BasicAuth
,以验证几个URL。有点像:

配置类

    @EnableWebSecurity
    @Configuration
    public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

        @Value("${auth.authenticated}")
        private String[] allAuthenticated;

        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.authorizeRequests()
                .antMatchers(allAuthenticated).authenticated()
                .and()
                .httpBasic();
        }

@Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) { 1
        auth
            .inMemoryAuthentication()
                .withUser("user").password("password").roles("USER").and()
                .withUser("admin").password("password").roles("USER", "ADMIN");
    }
// .... Rest of the code 

    }
application.yml

auth.authenticated: /onlineshop/v1/ecart,/onlineshop/v1/wishlist
它工作得很好,但我想对它进行单元测试

我正在考虑一个简单的测试用例,我可以直接向
/onlineshop/v1/ecart
/onlineshop/v1/wishlist
发出HTTP请求,并以某种方式检查它们是否经过身份验证

我偶然发现了这一点,并在课堂上进行了编码:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes=WebSecurityConfig.class)
public class BasicAuthTest {

    @Autowired
    private WebApplicationContext context;

    private MockMvc mvc;

    @Before
    public void setup() {
        mvc = MockMvcBuilders
                .webAppContextSetup(context)
                .apply(springSecurity()) 1
                .build();
    }

    @Test
    public void shouldBeAuthenticated() throws Exception {
        mvc.perform(get("/onlineshop/v1/ecart").with(httpBasic("user","password"))).andExpect(status().isOk());
    }


}
但每次它都给我404错误。所以我不确定我是否正确地配置了它或者什么

另外,如果有其他更好的方法来测试BasicAuth,请建议


谢谢

我不会把这称为单元测试。@Henry,请说明您在哪里配置了用户名和密码password@Jaiwo99,我使用了
configureGlobal()
。代码已更新。