質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.48%
JUnit

JUnitは、Javaで開発されたプログラムのユニットテストを行うためのアプリケーションフレームワークです。簡単にプログラムのユニットテストを自動化することができ、結果もわかりやすく表示されるため効率的に開発時間を短縮できます。

Java

Javaは、1995年にサン・マイクロシステムズが開発したプログラミング言語です。表記法はC言語に似ていますが、既存のプログラミング言語の短所を踏まえていちから設計されており、最初からオブジェクト指向性を備えてデザインされています。セキュリティ面が強力であることや、ネットワーク環境での利用に向いていることが特徴です。Javaで作られたソフトウェアは基本的にいかなるプラットフォームでも作動します。

Spring

Spring Framework は、Javaプラットフォーム向けのオープンソースアプリケーションフレームワークです。 Java Platform上に、 Web ベースのアプリケーションを設計するための拡張機能が数多く用意されています。

Spring Boot

Spring Bootは、Javaのフレームワークの一つ。Springプロジェクトが提供する様々なフレームワークを統合した、アプリケーションを高速で開発するために設計されたフレームワークです。

Q&A

解決済

3回答

7263閲覧

SpringBootでマッパークラスに対するテストが失敗する

khr-rock

総合スコア17

JUnit

JUnitは、Javaで開発されたプログラムのユニットテストを行うためのアプリケーションフレームワークです。簡単にプログラムのユニットテストを自動化することができ、結果もわかりやすく表示されるため効率的に開発時間を短縮できます。

Java

Javaは、1995年にサン・マイクロシステムズが開発したプログラミング言語です。表記法はC言語に似ていますが、既存のプログラミング言語の短所を踏まえていちから設計されており、最初からオブジェクト指向性を備えてデザインされています。セキュリティ面が強力であることや、ネットワーク環境での利用に向いていることが特徴です。Javaで作られたソフトウェアは基本的にいかなるプラットフォームでも作動します。

Spring

Spring Framework は、Javaプラットフォーム向けのオープンソースアプリケーションフレームワークです。 Java Platform上に、 Web ベースのアプリケーションを設計するための拡張機能が数多く用意されています。

Spring Boot

Spring Bootは、Javaのフレームワークの一つ。Springプロジェクトが提供する様々なフレームワークを統合した、アプリケーションを高速で開発するために設計されたフレームワークです。

1グッド

1クリップ

投稿2020/09/22 11:44

前提・実現したいこと

SpringBootで、Mybatisを利用したマッパーのテストクラスを作成してテストしている
テストして実際に値が取れることを確認したい
※DBはインメモリのH2

発生している問題・エラーメッセージ

テスト実行しても、AutowiredしたマッパーがNULLでテストに失敗する1
※SpringBootを起動して、実行する分には、AutowiredしたMapperにアクセスできる

JUNIT起動時に以下のメッセージがでて失敗する。

java.lang.NullPointerException at com.example.demo.SampleRepositoryTest2.contextLoads(SampleRepositoryTest2.java:26) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at

該当のソースコード

テストクラス

java

1package com.example.demo; 2 3import java.util.Optional; 4 5import org.junit.Test; 6import org.junit.jupiter.api.Assertions; 7import org.junit.runner.RunWith; 8import org.mybatis.spring.boot.test.autoconfigure.MybatisTest; 9import org.springframework.beans.factory.annotation.Autowired; 10import org.springframework.boot.test.context.SpringBootTest; 11import org.springframework.context.annotation.Import; 12import org.springframework.test.context.junit4.SpringRunner; 13 14import com.example.demo.repository.SampleRepository; 15import com.example.demo.repository.entity.Todo; 16 17@SpringBootTest(classes = SampleRepositoryTest2.class) 18@MybatisTest 19public class SampleRepositoryTest2 { 20 21 @Autowired 22 private SampleRepository repo; 23 24 @Test 25 public void contextLoads() throws Exception { 26 Optional<Todo> todo = repo.findById(1); 27 Assertions.assertEquals(todo.get().getTodoTitle(), "夜ごはんつくる"); 28 29 } 30} 31

リポジトリ

package com.example.demo.repository; import java.util.List; import java.util.Optional; import org.apache.ibatis.annotations.Insert; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Select; import org.springframework.stereotype.Repository; import com.example.demo.repository.entity.Todo; @Mapper public interface SampleRepository { @Select("select todo_id, todo_title, finished, created_at from todo where todo_id = #{id}") Optional<Todo> findById(Integer id); @Select("select todo_id, todo_title, finished, created_at from todo ") List<Todo> findAll(); @Select("SELECT COUNT(*) FROM todo WHERE finished = #{finished}") long countByFinished(boolean finished); @Insert("insert into todo ( todo_id, todo_title, finished, created_at ) values (#{todoId},#{todoTitle}, #{finished}, #{created_at})") void insert(Todo todo); }

\src\main\resources\data.sql

INSERT INTO todo ( todo_id, todo_title, finished, created_at ) VALUES ( 1, '朝ごはんつくる', false, '2020-12-01 09:15:00' ); INSERT INTO todo ( todo_id, todo_title, finished, created_at ) VALUES ( 2, '夜ごはんつくる', false, '2020-12-01 09:15:00' );

\src\main\resources\schema.sql

create table if not exists todo ( todo_id int, todo_title varchar(30), finished boolean, created_at timestamp );

build.gradle

plugins { id 'org.springframework.boot' version '2.3.2.RELEASE' id 'io.spring.dependency-management' version '1.0.9.RELEASE' id 'java' } group = 'com.example' version = '0.0.1-SNAPSHOT' sourceCompatibility = '1.8' repositories { mavenCentral() } ext { set('springCloudVersion', "Hoxton.SR7") } dependencies { implementation 'org.springframework.boot:spring-boot-starter-cache' implementation 'org.springframework.boot:spring-boot-starter-data-redis' implementation 'org.springframework.boot:spring-boot-starter-data-jdbc' implementation 'org.springframework.boot:spring-boot-starter-security' implementation 'org.springframework.boot:spring-boot-starter-thymeleaf' implementation 'org.springframework.boot:spring-boot-starter-web' implementation 'org.springframework.boot:spring-boot-starter-data-rest' implementation 'org.mybatis.spring.boot:mybatis-spring-boot-starter:2.1.3' implementation 'org.springframework.cloud:spring-cloud-starter-config' implementation 'org.springframework.boot:spring-boot-starter-actuator' developmentOnly 'org.springframework.boot:spring-boot-devtools' runtimeOnly 'com.h2database:h2' // implementation 'com.github.springtestdbunit:spring-test-dbunit:1.3.0' // implementation 'org.dbunit:dbunit:2.5.1' testImplementation 'org.springframework.boot:spring-boot-starter-test' testImplementation 'org.mybatis.spring.boot:mybatis-spring-boot-starter-test:2.1.3' testImplementation 'org.springframework.security:spring-security-test' compileOnly("org.projectlombok:lombok") } dependencyManagement { imports { mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}" } } test { useJUnitPlatform() }

パッケージ構成
イメージ説明

試したこと

build.gradleで、mybatisのテストライブラリのバージョンを以下に修正した。

http://mybatis.org/spring-boot-starter/mybatis-spring-boot-test-autoconfigure/
mybatisの公式を確認すると、、SpringBoot2.1以上は、mybatisのテストライブラリのバージョンが2.1が指定されていたため

修正前

implementation 'org.mybatis.spring.boot:mybatis-spring-boot-starter-test:1.3.4'

修正後

testImplementation 'org.mybatis.spring.boot:mybatis-spring-boot-starter-test:2.1.3'

補足情報(FW/ツールのバージョンなど)

IDE
Spring Tool Suite Version: 3.9.7.RELEASE

A-pZ👍を押しています

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

回答3

0

そもそもテスト起動時にDIコンテナが起動する想定だが起動していなかったので、テストクラスを新規で作りなしたら、うまく動作した。(これ自体の原因は不明)

※Mybatisのテストでは余計なアノテーションを削除して、「@MybatisTest」のみでテストできることも確認できた。

投稿2020/10/07 13:42

khr-rock

総合スコア17

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

0

ベストアンサー

mybatis-spring-boot-starter-test:2.1.3 をお使いの場合は、もう少し簡略化できます。

また、@SpringBootTestに設定するクラスは「Spring用の設定クラス名」ですので、この場合不要です。

もしJUnit4系を使う場合は、@RunWith(SpringRunner.class)を記述します。
JUnit5系を使う場合は、@RunWithの記載も不要です。

http://mybatis.org/spring-boot-starter/mybatis-spring-boot-test-autoconfigure/ の 「Using @MybatisTest on JUnit 5」近辺を参照に。

java

1@MybatisTest 2public class SampleRepositoryTest2 { 3 4 @Autowired 5 SampleRepository repo; 6 7 @Test 8 public void contextLoads() throws Exception { 9 Optional<Todo> todo = repo.findById(1); 10 Assertions.assertEquals(todo.get().getTodoTitle(), "夜ごはんつくる"); 11 12 } 13}

投稿2020/09/23 04:05

編集2020/09/23 11:52
A-pZ

総合スコア12011

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

khr-rock

2020/10/06 15:16 編集

返信が遅れ申し訳ないです。回答ありがとうございます。 該当のリンクを確認して以下の記載があったので、@MyBatisTest以外を除いて試してみたのですが、エラーが変わりませんでした。 >Since 2.0.1, the @ExtendWith(SpringExtension.class) can omit as follow: @MybatisTest Autowiredを利用しているのでDIコンテナがインスタンスを作る認識ですが、テストするとSpringBootが起動するまでもなく落ちてしまっています。(SpringBootという文字がコンソールにでない) 何か設定が良くないのかなと考えています。
A-pZ

2020/10/07 04:14

@SpringBootTest(classes = SampleRepositoryTest2.class) の記述も不要ではないかと思います。
khr-rock

2020/10/07 13:39

回答ありがとうございます。 テストですが、新しく作り直すと上手く動きました、、ちょっと原因は分からないですが、解決しました。。。。 また@SpringBootTest(classes = SampleRepositoryTest2.class) を消して、「@MybatisTest」のみでテストできることも確認しました。助かりました。
guest

0

Autowiredは、Spring動かさないとDIされないはずですが、

@RunWith(SpringRunner.class)

がなくても動くんですっけ?

@SpringBootTestがコンフィグレーションを自動検出する仕組み - Qiita

投稿2020/09/22 13:23

szk.

総合スコア1400

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

khr-rock

2020/10/06 15:08 編集

返信が遅れ申し訳ないです。回答ありがとうございます。 Junit5を利用していました。なので@ExtendWithに置き換わったので、@Runwithは使わない認識です。
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.48%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問