LoginSignup
1
0

More than 1 year has passed since last update.

Valueを付与した変数にJUnitでモックする

Posted at

Valueを付与した変数にJUnitでモックする方法

概要

  • @Valueを付与した変数を扱うクラスのテストを実施した際、@Valueの変数の値がテスト時のみnullとなってしまう事象が発生

  • 以下テスト対象のクラス

@Component
public class HogeService {

  @Value("${sample.variable}")
  private String sampleVariable;   ここの変数がテストでnullで返ってくる
...

↑の件、少し解決につまづいたので、解決方法を記載

結論

  • org.springframework.test.util.ReflectionTestUtilsを利用することでmockできる
ReflectionTestUtils.setField(instance, "name", "value", String.class);

サンプル

  • @Valueを利用しているクラス
@Component
public class HogeService {

  @Value("${sample.variable}")
  private String sampleVariable;
...
  • @Valueを利用しているクラスのテストコード
@ExtendWith(MockitoExtension.class)
public class HogeServiceTest {

  @InjectMocks
  private HogeService hogeService;

  @BeforeEach
  private void setup() {
    ReflectionTestUtils.setField(
        hogeService,
        "sampleVariable",
        "test",
        String.class);
  }
...

理由

  • @Valueは外部から値をインジェクションしているため、JUnitでテストを実施する際もmockの設定をしなければ、外部のファイルから自動で読み取ってくれないので、@Valueを付与した変数は値がnullになってしまう
  • そのため、テストでは@Valueを付与した変数にReflectionTestUtils.setFieldを利用し、値をインジェクションすることで解決

補足

@Valueとは

  • @Valueは別のファイルから値をインジェクションしたいときに用いるアノテーション
  • application.ymlやapplication.propertiesに記載されている値を読み取ると気に利用する

  • 読み取り先のファイル
application.yml
sample:
  hoge: test
  • 指定方法
@Value("{sample.hoge}")
private String sampleHoge;
...

参考

1
0
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
1
0