【问题标题】:Spring Boot junit testing secured applicationSpring Boot junit 测试安全应用程序
【发布时间】:2018-07-22 00:29:19
【问题描述】:

我在我的应用程序中使用 Spring Security OAuth2。当我尝试使用 JUnit 测试来测试服务层时,我收到了这个错误:

org.springframework.security.authentication.AuthenticationCredentialsNotFoundException: 在 SecurityContext 中找不到 Authentication 对象

你能告诉我如何解决它吗?

这是我的测试类:

@RunWith(SpringRunner.class)
@SpringBootTest
@Transactional
public class FooServiceTest {

    @Autowired
    private FooService service;

    @Test
    public void someTest() {    
        service.findFoo(1L);
    }
}

【问题讨论】:

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


【解决方案1】:

使用@WithMockUser

@WithMockUser(username = "usertest", password = "password", roles = "USER")
@RunWith(SpringRunner.class)
@SpringBootTest
@Transactional
public class FooServiceTest {

    @Autowired
    private FooService service;

    @Test
    public void someTest() {    
        service.findFoo(1L);
    }

}

【讨论】:

    猜你喜欢
    • 2022-10-24
    • 2021-05-17
    • 2021-11-24
    • 2019-10-09
    • 1970-01-01
    • 1970-01-01
    • 2018-07-11
    • 1970-01-01
    • 2019-10-26
    相关资源
    最近更新 更多