LoginSignup
3
2

More than 5 years have passed since last update.

AuthenticationProvider を JUnit からテストできなかった話

Posted at

概要

Spring Boot にて Spring Security の機能を使い認証処理を実装しました。
データソースはデータベースではなく別 Web サービスにあるため、Spring Data JPA での認証が行えないため、AuthenticationProvider にて認証処理を実装しました。

JUnit での失敗

JUnit を実行したところ、下記エラーが発生しました。

java.lang.IllegalStateException: Unable to find a @SpringBootConfiguration, you need to use @ContextConfiguration or @SpringBootTest(classes=...) with your test

AuthenticationProvider 実装後、アプリケーションを起動すると、 無事ページ上からの要求においては、 AuthenticationProvider が起動しました。

正しい方法

AuthenticationProvider をインジェクションする場合は、エラー時のメッセージにあるとおり、@ContextConfiguration が必要なようです。
@ContextConfiguration の引数には SpringBoot の起動クラスを指定します。


@ContextConfiguration(classes = HogeApplication.class)
public class AuthencationTest {
      ... something to test ....
}

なお、ContextConfiguration の引数に変なものを指定するとエラーになります。

Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'securityConfig': Unsatisfied dependency expressed through field 'authenticationProvider'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.security.authentication.AuthenticationProvider' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2