はじめに
SpringBootでテストを、となった際にテストサイズを考えsmall testのUnitテストを実装したいという場面があるが、small testをどのように実装するのかについて記載した記事をあまり見かけないので、自身の備忘録としても残しておく。
※ググると大抵dependencyにspring test
系を持たせているものが見つかるが、ミニマムのunit testを実装する上ではそれらは不要。
この記事を読むと分かる事は以下。
- SpringBootにおけるjMockitでのsmall testを導入する際の依存関係(pom.xmlの内容)
- DI(
@Autowired
)されているフィールドの扱い方などテストコードの基本的な書き方
small testとは
カバレッジの話
JUnit5×jMockitでsmall test
SpringBootにおけるjMockitでのsmall testを導入する際の依存関係(pom.xmlの内容)
プロジェクト(パッケージ)管理ツールにmavenを使っている場合、pom.xmlは以下のようになる。
※色々省略しているが、samll testであれば基本的にspring-boot-starter-test
などの依存は不要。
<project xmlns="・・・">
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.4.5</version>
</parent>
<properties>
<junit-jupiter.version>5.7.1</junit-jupiter.version>
<jmockit.version>1.49</jmockit.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- jdbc, json, lombokなどなど -->
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jmockit</groupId>
<artifactId>jmockit</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</project>
DI(@Autowired)されているフィールドの扱い方などテストコードの基本的な書き方
まずjMockitを使うため、@ExtendWith
でJMockitExtension.class
を宣言し継承する。
SpringでDI(@Autowired
)されている各フィールドは@Injectable
でmock化する。
また、それらをtest対象のクラスにinjectするために、test対象クラスに対しては@Tested
を記載しmockを注入する。
基本的なパターンとしては以下のような実装になる。
※jMockitの使い方・構文についてはここを参照。
※SpringでのjMockitについてはここを参照。
// 省略
@ExtendWith(JMockitExtension.class)
class SampleTest {
@Injectable
private Hoge mockHoge;
@Injectable
private Fuga mockFuga;
@Tested
private Sample testClass;
@Test
void testFoo() {
mockGetHoge("hoge");
assertEquals("hoge", testClass.foo());
}
private void mockGetHoge(String resultValue) {
new Expectations() {
{
mockHoge.getHoge();
result = resultValue;
}
};
}
// 省略
}