Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

This article is a Private article. Only a writer and users who know the URL can access it.
Please change open range to public in publish setting if you want to share this article with other users.

More than 1 year has passed since last update.

SpringBootでAPIサーバを起動してテストする時のメモ

Last updated at Posted at 2022-11-01

環境

確認時の環境:Spring-Boot 2.7.x + JUnit5

メモ

SpringBootのAPIサーバを起動してテストする

公式サイト の「アプリケーションをテストする」部分

@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class APITest {
/** ...略... */
}

起動したAPIサーバに対してリクエストを投げてテストする

公式サイト の「アプリケーションをテストする」部分
localhostに対して restTemplate 使ってリクエストを投げる形。

@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class APITest {

	@LocalServerPort
	private int port;

	@Autowired
	private TestRestTemplate restTemplate;

	@Test
	public void greetingShouldReturnDefaultMessage() throws Exception {
		assertThat(this.restTemplate.getForObject("http://localhost:" + port + "/",
				String.class)).contains("Hello, World");
    /** ...略... */
}

コントローラの中のサービスをモック化したい場合

@MockBean or @SpyBean を使う。
@InjectMocksMockitoAnnotations.initMocks は不要。

@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class APITest {

    /** ...略... */
    @Mockbean
    HogeService hogeService;
    /** ...略... */
}

モックの動作の書き方は Mockito。

参照

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?