可以使用MockMvc测试受Spring Security保护的控制器吗?

问题描述 投票:0回答:1

我试图弄清楚,什么是测试Spring Boot应用程序安全性配置的最佳方法。我的目标是进行两个测试:

  • 授予用户A,在401中访问资源/测试结果
  • 授予用户B,获得资源/测试结果的权限为200

[开始研究时,我发现的所有教程都指向“ MockMvc”,但是我无法编写2种以这种方式工作的测试。在我看来,几乎在所有情况下,安全性都被完全忽略(即使没有提供任何用户,MockMvc也会返回200。)

举个简单的例子,我有以下设置:

安全配置:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

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

}

控制器:

@RestController
public class TestController {

    @GetMapping("/test")
    public String getTest() {
        return "hello";
    }

}

属性:

spring.security.user.name=testuser
spring.security.user.password=testpassword

我可以使用“ TestRestTemplate”像这样成功地测试它:

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class DemoApplicationTests {

    @Autowired
    private TestRestTemplate testRestTemplate;

    @Test
    void when_userIsValid_should_return200() throws Exception {
        String res = testRestTemplate
                .withBasicAuth("testuser", "testpassword")
                .getForEntity("/test", String.class)
                .getBody();
        Assert.assertEquals("hello", res);
    }

    @Test
    void when_userIsInvalid_should_return401() throws Exception {
        HttpStatus res = testRestTemplate
                .withBasicAuth("foo", "bar")
                .getForEntity("/test", String.class)
                .getStatusCode();
        Assert.assertEquals(HttpStatus.UNAUTHORIZED, res);
    }

}

所以我的问题是:这是“前进的道路”吗?如果选择MockMvc作为工具,能否请您提供一个可行的示例?我已经尝试了30种来自Tutorials和Stackoverflow的解决方案,但都没有成功(MockMvc为null,安全性被完全忽略,不再检测到Controller Method,而且我太愚蠢而无法使它们工作:/)

谢谢你!

我试图弄清楚,什么是测试Spring Boot应用程序安全性配置的最佳方法。我的目标是进行两个测试:给定用户A,在401中访问资源/测试结果给定...

spring-boot integration-testing mockmvc
1个回答
0
投票

您可以使用WebMvcTest仅初始化Controller层(它不会创建/注入所有其他定义了服务/存储库的Spring Bean,等等。但是当测试Controller逻辑时,它是合适的(并且更快)。

© www.soinside.com 2019 - 2024. All rights reserved.