Denis Stephanov
Denis Stephanov

Reputation: 5231

Spring Boot junit testing secured application

I am using in my application Spring Security OAuth2. When I try to test the service layer with JUnit tests I get this error:

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

Can you tell me how to fix it?

Here is my Test class:

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

    @Autowired
    private FooService service;

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

Upvotes: 1

Views: 2039

Answers (1)

Subin Chalil
Subin Chalil

Reputation: 3660

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

}

Upvotes: 5

Related Questions