LoginSignup
2
0

More than 1 year has passed since last update.

@Value でファイルから読み取った値を JUnit でモックする

Posted at

動作環境

  • Spring Boot v2.4
  • JUnit v5.7

結論

org.springframework.test.util.ReflectionTestUtils で mock できる。
@Value を付与しているフィールドに値が付与される。

ReflectionTestUtils.setField(instance, "name", "value", String.class);

理由

mock をしないとテスト実行で値が null となってしまう。

具体的には

例えば @Value を利用しているクラス。
org.springframework.beans.factory.annotation.Value

FooService.class
@Service
@RequiredArgsConstructor
public class FooService {
  @Value("${app.configValue}")
  private String configValue;

上記に対するテスト。
インスタンスを生成する必要がある。

FooServiceTest.class
@ExtendWith(MockitoExtension.class)
class FooServiceTest {
  @Spy
  @InjectMocks
  private FooService fooService;

@BeforeEach
  public void beforeEach() throws IOException {
    mapper = mock(fooMapper.class);
    service = spy(new FooService(mapper));

    ReflectionTestUtils.setField(service, "configValue", "bar", String.class);
  }

テスト対象のクラスで @RequiredArgsConstructor (lombok.RequiredArgsConstructor) を利用しており引数付きでインスタンスを作成する場合には、こんな雰囲気の記述でモックできる。

参考

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