SpringとSpockを使用したテスト
1. 前書き
この短いチュートリアルでは、Spring Bootのtesting frameworkのサポート力と、ユニット用かintegration tests用かを問わずSpock frameworkの表現力を組み合わせる利点を示します。 。
2. プロジェクトのセットアップ
簡単なWebアプリケーションから始めましょう。 簡単なREST呼び出しで、挨拶、挨拶の変更、およびデフォルトへのリセットを行うことができます。 メインクラスとは別に、単純なRestControllerを使用して機能を提供します。
@RestController
@RequestMapping("/hello")
public class WebController {
@GetMapping
public String salutation() {
return "Hello world!";
}
}
そのため、コントローラーは「Hello world!」と挨拶します。 @RestControllerアノテーションとshortcut annotationsは、RESTエンドポイントの登録を保証します。
3. MavenDependencies for Spock and Spring Boot Test
Maven依存関係を追加することから始め、必要に応じてMavenプラグイン構成を追加します。
3.1. SpringサポートによるSpockフレームワークの依存関係の追加
Spock itselfとSpring supportには、2つの依存関係が必要です。
org.spockframework
spock-core
1.2-groovy-2.4
test
org.spockframework
spock-spring
1.2-groovy-2.4
test
バージョンは、使用されているgroovyバージョンへの参照であることに注意してください。
3.2. Spring Bootテストの追加
Spring Boot Testのテストユーティリティを使用するには、次の依存関係が必要です。
org.springframework.boot
spring-boot-starter-test
2.1.1.RELEASE
test
3.3. Groovyをセットアップする
また、SpockはGroovyに基づいているため、we have to add and configure the gmavenplus-plugin as well はテストでこの言語を使用できるようになります。
org.codehaus.gmavenplus
gmavenplus-plugin
1.6
compileTests
テスト目的でのみGroovyが必要であるため、プラグインの目標をcompileTestに制限していることに注意してください。
4. スポックテストでのApplicationContextのロード
簡単なテストの1つは、check if all Beans in the Spring application context are createdです。
@SpringBootTest
class LoadContextTest extends Specification {
@Autowired (required = false)
private WebController webController
def "when context is loaded then all expected beans are created"() {
expect: "the WebController is created"
webController
}
}
この統合テストでは、ApplicationContextを起動する必要があります。これは、@SpringBootTestが行うことです。 Spockは、「when”」、「then”」、「expect”」などのキーワードを使用して、テストでセクションを分離します。
さらに、ここでのテストの最後の行として、Groovy Truthを利用してBeanがnullかどうかを確認できます。
5. スポックテストでのWebMvcTestの使用
同様に、WebControllerの動作をテストできます。
@AutoConfigureMockMvc
@WebMvcTest
class WebControllerTest extends Specification {
@Autowired
private MockMvc mvc
def "when get is performed then the response has status 200 and content is 'Hello world!'"() {
expect: "Status is 200 and the response is 'Hello world!'"
mvc.perform(get("/hello"))
.andExpect(status().isOk())
.andReturn()
.response
.contentAsString == "Hello world!"
}
}
スポックテスト(またはSpecifications) we can use all familiar annotations from the Spring Boot test framework that we are used to.)では注意することが重要です
6. 結論
この記事では、SpockとSpringBootテストフレームワークを組み合わせて使用するようにMavenプロジェクトを設定する方法について説明しました。 さらに、両方のフレームワークが互いに完全に補完する方法を見てきました。
詳細については、testing with Spring Boot、Spock framework、およびGroovy languageに関するチュートリアルをご覧ください。
最後に、追加の例を含むソースコードは、GitHub repositoryにあります。