1
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Serviceの単体テストを整理する(SpringBoot)

Posted at

はじめに

ここまでに、Controllerと、DBアクセス部分の単体テストについて整理してきました。

最後にService層の単体テストを整理したいと思います。

環境

Windows 11
Eclipse
Java21
Gradle
Spring Boot 3.4.0
Spring Boot Test 3.4.0
Lombok
Mockito 5.14.2

単体テスト方針

以下のような方針でテストの実行方法を検討することにします。
ここでは具体的なテストケース、検証内容には触れません

・モックを利用する
・メソッドの呼び出し回数、引数をチェックする
・実行結果及び応答値を検証する

※基本的な考え方は、Controllerと同じです。

やってみる

テスト対象クラス

User.java
@Data
@AllArgsConstructor 
public class User {
	long id;
	String name;
}

UserMapper.java
@Mapper
public interface UserMapper {
	User findById(int id);
}
UserService.java
@Service
public class UserService {

    private final UserMapper userMapper;

    public UserService(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    public User getUserById(int id) {
        return userMapper.findById(id);
    }
}

テストクラス

UserServiceTest.java

@ExtendWith(MockitoExtension.class) // Mockitoを有効化
public class UserServiceTest {

	@InjectMocks
	private UserService userService;

	@Mock
	private UserMapper userMapper;

	@Test
	void testGetUserById() {
		// モックの設定
		User mockUser = new User(1, "John Doe");
		when(userMapper.findById(1)).thenReturn(mockUser);

		// サービスメソッドを呼び出し
		User result = userService.getUserById(1);

		// 結果を検証
		assertNotNull(result);
		assertEquals("John Doe", result.getName());
		verify(userMapper, times(1)).findById(1);
	}
}

実行する

Eclipseで実行するとこんな感じです。

image.png

さいごに

Mockitoの使い方は、Controllerの時とほぼ同じですが、
今回のテストクラスはSpringに依存しないMockitoとして作りました(コンテナの初期化とか余計な時間がかからない)

またここまでの整理で、サーバサイドの各レイヤでの単体テストが整理できたので
現場のプロジェクトでも展開していきたいと思います。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?