Spring Boot junit测试安全应用程序

时间:2018-02-11 20:43:56

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

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

  

org.springframework.security.authentication.AuthenticationCredentialsNotFoundException:   在SecurityContext

中找不到Authentication对象

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

这是我的Test类:

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

    @Autowired
    private FooService service;

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

1 个答案:

答案 0 :(得分: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);
    }

}