gpt4 book ai didi

java - Spring Boot junit 测试安全应用程序

转载 作者:行者123 更新时间:2023-12-02 11:38:40 25 4
gpt4 key购买 nike

我在我的应用程序中使用 Spring Security OAuth2。当我尝试使用 JUnit 测试来测试服务层时,出现以下错误:

org.springframework.security.authentication.AuthenticationCredentialsNotFoundException: An Authentication object was not found in the SecurityContext

你能告诉我如何解决这个问题吗?

这是我的测试类:

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

@Autowired
private FooService service;

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

最佳答案

使用@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);
}

}

关于java - Spring Boot junit 测试安全应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48736265/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com