1 В избранное 0 Ответвления 0

OSCHINA-MIRROR/chanjarster-spring-test-examples

Присоединиться к Gitlife
Откройте для себя и примите участие в публичных проектах с открытым исходным кодом с участием более 10 миллионов разработчиков. Приватные репозитории также полностью бесплатны :)
Присоединиться бесплатно
Клонировать/Скачать
chapter_5_mvc.md 6.5 КБ
Копировать Редактировать Web IDE Исходные данные Просмотреть построчно История
gitlife-traslator Отправлено 27.11.2024 23:55 3b54fb2

Тестирование Spring MVC

Spring Testing Framework предоставляет Spring MVC Test Framework, который позволяет удобно тестировать Controller. Spring Boot также предлагает Auto-configured Spring MVC tests, что ещё больше упрощает процесс настройки тестирования.

В этой главе мы рассмотрим примеры тестирования Spring MVC без использования Spring Boot и с использованием Spring Boot.

Пример 1: Spring

Ключевым элементом тестирования Spring MVC является использование объекта MockMvc, который позволяет тестировать поведение Controller без запуска Servlet контейнера.

Исходный код SpringMvc_1_Test.java:

@EnableWebMvc
@WebAppConfiguration
@ContextConfiguration(classes = { FooController.class, FooImpl.class })
public class SpringMvc_1_Test extends AbstractTestNGSpringContextTests {

  @Autowired
  private WebApplicationContext wac;

  private MockMvc mvc;

  @BeforeMethod
  public void prepareMockMvc() {
    this.mvc = webAppContextSetup(wac).build();
  }

  @Test
  public void testController() throws Exception {

    this.mvc.perform(get("/foo/check-code-dup").param("code", "123"))
        .andDo(print())
        .andExpect(status().isOk())
        .andExpect(content().string("true"));

  }
}

Здесь есть три основных шага:

  • Маркировка тестового класса как @WebAppConfiguration.
  • Создание MockMvc через webAppContextSetup(wac).build().
  • Использование MockMvc для оценки результатов.

Пример 2: Spring + Mock

В примере 1 FooController использует Bean из сущности FooImpl. Однако мы можем предоставить mock bean для Foo, чтобы лучше контролировать процесс тестирования. Если вы не знакомы с Mock, рекомендуется обратиться к главе 3: Использование Mockito.

Исходный код SpringMvc_2_Test.java:

@EnableWebMvc
@WebAppConfiguration
@ContextConfiguration(classes = { FooController.class })
@TestExecutionListeners(listeners = MockitoTestExecutionListener.class)
public class SpringMvc_2_Test extends AbstractTestNGSpringContextTests {

  @Autowired
  private WebApplicationContext wac;

  @MockBean
  private Foo foo;

  private MockMvc mvc;

  @BeforeMethod
  public void prepareMockMvc() {
    this.mvc = webAppContextSetup(wac).build();
  }

  @Test
  public void testController() throws Exception {

    when(foo.checkCodeDuplicate(anyString())).thenReturn(true);

    this.mvc.perform(get("/foo/check-code-dup").param("code", "123"))
        .andDo(print())
        .andExpect(status().isOk())
        .andExpect(content().string("true"));

  }
}

Пример 3: Spring Boot

Spring Boot предлагает @WebMvcTest, что упрощает тестирование Spring MVC. Мы предоставляем пример, соответствующий примеру 1, но на основе Spring Boot.

Исходный код BootMvc_1_Test.java:

@WebMvcTest
@ContextConfiguration(classes = { FooController.class, FooImpl.class })
public class BootMvc_1_Test extends AbstractTestNGSpringContextTests {

  @Autowired
  private MockMvc mvc;

  @Test
  public void testController() throws Exception {

    this.mvc.perform(get("/foo/check-code-dup").param("code", "123"))
        .andDo(print())
        .andExpect(status().isOk())
        .andExpect(content().string("true"));

  }
}

Здесь нам не нужно создавать MockMvc самостоятельно — достаточно использовать @Autowired для его внедрения.

Пример 4: Spring Boot + Mock

Это версия примера 2 на основе Spring Boot. Исходный код BootMvc_2_Test.java:

@WebMvcTest
@ContextConfiguration(classes = { FooController.class })
@TestExecutionListeners(listeners = MockitoTestExecutionListener.class)
public class BootMvc_2_Test extends AbstractTestNGSpringContextTests {

  @Autowired
  private MockMvc mvc;

  @MockBean
  private Foo foo;

  @Test
  public void testController() throws Exception {

    when(foo.checkCodeDuplicate(anyString())).thenReturn(true);

    this.mvc.perform(get("/foo/check-code-dup").param("code", "123"))
        .andDo(print())
        .andExpect(status().isOk())
        .andExpect(content().string("true"));

  }
}
``` [глава_3_mockito]: chapter_3_mockito.md
[руководство по тестированию веб-слоя]: https://spring.io/guides/gs/testing-web/
[документ spring framework тестирование]: http://docs.spring.io/spring/docs/4.3.9.RELEASE/spring-framework-reference/htmlsingle/#testing
[документ spring WebApplicationContext]: https://docs.spring.io/spring/docs/4.3.9.RELEASE/spring-framework-reference/html/integration-testing.html#testcontext-ctx-management-web
[документ spring boot тестирование]: http://docs.spring.io/spring-boot/docs/1.5.4.RELEASE/reference/htmlsingle/#boot-features-testing
[javadoc AutoConfigureMockMvc]: http://docs.spring.io/spring-boot/docs/1.5.4.RELEASE/api/org/springframework/boot/test/autoconfigure/web/servlet/AutoConfigureMockMvc.html
[документ автонастраиваемые тесты spring mvc]: http://docs.spring.io/spring-boot/docs/1.5.4.RELEASE/reference/htmlsingle/#boot-features-testing-spring-boot-applications-testing-autoconfigured-mvc-tests
[документ spring mvc тестовая среда]: https://docs.spring.io/spring/docs/4.3.9.RELEASE/spring-framework-reference/htmlsingle/#spring-mvc-test-framework
[gh spring mvc официальный образец тестов]: https://github.com/spring-projects/spring-framework/tree/master/spring-test/src/test/java/org/springframework/test/web/servlet/samples
[gh spring mvc showcase]: https://github.com/spring-projects/spring-mvc-showcase
[src SpringMvc_1_Test.java]: mvc/src/test/java/me/chanjar/spring1/SpringMvc_1_Test.java
[src SpringMvc_2_Test.java]: mvc/src/test/java/me/chanjar/spring2/SpringMvc_2_Test.java
[src BootMvc_1_Test.java]: mvc/src/test/java/me/chanjar/springboot1/BootMvc_1_Test.java
[src BootMvc_2_Test.java]: mvc/src/test/java/me/chanjar/springboot2/BootMvc_2_Test.java

Опубликовать ( 0 )

Вы можете оставить комментарий после Вход в систему

1
https://api.gitlife.ru/oschina-mirror/chanjarster-spring-test-examples.git
git@api.gitlife.ru:oschina-mirror/chanjarster-spring-test-examples.git
oschina-mirror
chanjarster-spring-test-examples
chanjarster-spring-test-examples
master