Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the implementation method of SpringBoot application test

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article introduces the relevant knowledge of "what is the implementation method of SpringBoot application testing". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

For Web applications, when an application involves data layer, service layer, Web layer, and the interaction between various external services, we not only unit test the components of each layer, but also fully introduce integration testing to ensure the correctness and stability of the service.

Test solution in Spring Boot

Like the Spring Boot 1.x version, Spring Boot 2.x provides a spring-boot-starter-test component for testing.

In Spring Boot, the way to integrate this component is to add the following dependencies in the pom file:

Org.springframework.boot spring-boot-starter-test test org.junit.platform junit-platform-launcher test

The last dependency is used to import functional components related to JUnit.

Then, by looking at the dependency of the spring-boot-starter-test component through Maven, we can get the component dependency graph shown below:

As you can see from the above figure, in the build path of the code project, we introduced a series of components to initialize the test environment. Such as JUnit, JSON Path, AssertJ, Mockito, Hamcrest, etc.

JUnit:JUnit is a very popular unit testing framework based on Java language.

JSON Path: similar to the positioning of XPath in XML documents, JSON Path expressions are commonly used to retrieve paths or set data in JSON files.

AssertJ:AssertJ is a powerful streaming assertion tool that needs to follow the core principles of 3A, namely Arrange (initializing test objects or preparing test data)-> Actor (calling methods under test)-> Assert (executing assertions).

Mockito:Mockito is a popular Mock testing framework in the Java world, which mainly uses concise API to simulate operations. We will make extensive use of this framework when implementing integration testing.

Hamcrest:Hamcrest provides a set of matchers (Matcher), where each matcher is designed to perform specific comparison operations.

JSONassert:JSONassert is an assertion framework specifically for JSON.

Spring Test & Spring Boot Test: testing tools for the Spring and Spring Boot frameworks.

The dependencies of the above components are imported automatically without making any changes.

Test the Spring Boot application

Next, we will initialize the test environment for the Spring Boot application and show you the methods and techniques for completing unit testing within a single service.

After importing the spring-boot-starter-test dependency, we can use the features it provides to deal with complex test scenarios.

Initialize the test environment

For Spring Boot applications, we know that the main () entry in its Bootstrap class will launch the Spring container through the SpringApplication.run () method.

Import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplicationpublic class Application {public static void main (String [] args) {SpringApplication.run (Application.class, args);}}

For the above Bootstrap classes, we can verify that the Spring container can be started properly by writing test cases.

Based on the default style of Maven, we will add various test case code and configuration files under the src/test/java and src/test/resources packages.

Import org.junit.Assert;import org.junit.Test;import org.junit.runner.RunWith;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.test.context.SpringBootTest;import org.springframework.context.ApplicationContext;import org.springframework.test.context.junit4.SpringRunner; @ SpringBootTest@RunWith (SpringRunner.class) public class ApplicationContextTests {@ Autowired private ApplicationContext applicationContext; @ Test public void testContextLoads () throws Throwable {Assert.assertNotNull (this.applicationContext);}}

This use case makes a simple non-null verification of ApplicationContext in Spring.

After the test case is executed, from the output console information, we can see that the Spring Boot application is started normally, and the test case itself gives a hint of a successful execution.

Although the above test case is simple, it already contains the basic code framework for testing Spring Boot applications. The most important of these are the @ SpringBootTest and @ RunWith annotations on the ApplicationContextTests class, which constitute a complete test scenario for SpringBoot applications.

Next, let's expand these two annotations in detail.

@ SpringBootTest

Because the entry to the SpringBoot program is the Bootstrap class, SpringBoot specifically provides a @ SpringBootTest annotation to test the Bootstrap class. At the same time, the @ SpringBootTest annotation can also reference the configuration of the Bootstrap class, because all configurations are loaded through the Bootstrap class.

In the above example, we tested the Application class as a Bootstrap class by directly using the default functionality provided by the @ SpringBootTest annotation.

A more common practice is to specify the Bootstrap class in the @ SpringBootTest annotation and set up the Web environment for the test, as shown in the following code.

@ SpringBootTest (classes = CustomerApplication.class, webEnvironment = SpringBootTest.WebEnvironment.MOCK)

In the above code, the webEnvironment in the @ SpringBootTest annotation can have four options, namely MOCK, RANDOM_PORT, DEFINED_PORT, and NONE.

@ SpringBootTest-webEnvironment

MOCK: load WebApplicationContext and provide a Servlet environment for Mock, while the built-in Servlet container is not officially launched.

RANDOM_PORT: load EmbeddedWebApplicationContext and provide a real Servlet environment, then start the built-in container using a random port.

DEFINED_PORT: this configuration also provides a real Servlet environment by loading EmbeddedWebApplicationContext, but uses the default port, or 8080 if no port is configured.

NONE: loads ApplicationContext but does not provide any real Servlet environment.

In SpringBoot, the @ SpringBootTest annotation is mainly used to test ApplicationContext based on autoconfiguration, which allows us to set up the Servlet environment in the test context.

In most scenarios, a real Servlet environment is too heavyweight for testing, and the trouble caused by this environmental constraint can be alleviated through the MOCK environment.

@ RunWith comments and SpringRunner

In the above example, we also see a @ RunWith annotation provided by the JUnit framework that is used to set up the test runner. For example, we can have the test run in the Spring test environment through @ RunWith (SpringJUnit4ClassRunner.class).

Although we specify SpringRunner.class, in fact, SpringRunner is a simplification of SpringJUnit4ClassRunner, which allows JUnit and Spring TestContext to run together, while Spring TestContext provides general support for testing Spring applications.

Execute test cases

Next, we will review the process and practice of using the JUnit framework to perform unit tests through code examples, while providing test methods for verifying exceptions and verifying correctness.

The application scenario of unit testing is an independent class, and the CustomerTicket class shown below is a very typical independent class:

Public class CustomTicket {private Long id; private Long accountId; private String orderNumber; private String description; private Date createTime; public CustomTicket (Long accountId, String orderNumber) {super (); Assert.notNull (accountId, "Account Id must not be null"); Assert.notNull (orderNumber, "Order Number must not be null"); Assert.isTrue (orderNumber.length () = = 10, "Order Number must be exactly 10 characters") This.accountId = accountId; this.orderNumber = orderNumber;}... }

We can see that this class encapsulates CustomTicket and adds a check mechanism to its constructor.

Let's take a look at how to test a normal scenario.

For example, for the length of orderNumber in ArtisanTicket, we can use the following test case to verify the correctness of the rule by passing a string in the constructor:

@ RunWith (SpringRunner.class) public class CustomerTicketTests {private static final String ORDER_NUMBER = "Order00001"; @ Test public void testOrderNumberIsExactly10Chars () throws Exception {CustomerTicket customerTicket = new CustomerTicket (100L, ORDER_NUMBER); assertThat (customerTicket.getOrderNumber (). ToString ()) .isEqualTo (ORDER_NUMBER);} use @ DataJpaTest annotation to test the data access component

Data needs to be persisted, and then we will discuss how to test the Repository layer from the perspective of data persistence.

First, we discuss the scenario of using a relational database and introduce the @ DataJpaTest annotation for JPA data access technology.

The @ DataJpaTest annotation automatically injects various Repository classes and initializes an in-memory database and a data source that accesses the database. In the test scenario, we can generally use H2 as the in-memory database and persist the data through MySQL, so we need to introduce the Maven dependency shown below:

Com.h3database h3 mysql mysql-connector-java runtime

On the other hand, we need to prepare the database DDL to initialize the database tables and provide DML scripts to complete the data initialization. Among them, schema-mysql.sql and data-h3.sql scripts act as DDL and DML respectively.

The create statement for the CUSTOMER table is included in the schema-mysql.sql of customer-service, as shown in the following code:

DROP TABLE IF EXISTS `customerticket`; create table `customerticket` (`id` bigint (20) NOT NULL AUTO_INCREMENT, `order_ id` bigint (20) not null, `order_ number`varchar (50) not null, `substitution`varchar (100) not null, `create_ time`timestamp not null DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (`id`))

In data-h3.sql, we insert a piece of data that the test needs to use. The specific process of initializing the data is as follows:

INSERT INTO customerticket (`account_ id`, `order_ number`, `substitution`) values (1, 'Order00001',' DemoCustomerTicket1')

The next step is to provide a specific Repository interface. Let's review the definition of the CustomerRepository interface with the code shown below.

Public interface CustomerTicketRepository extends JpaRepository {List getCustomerTicketByOrderNumber (String orderNumber);}

There is a method name derivative query getCustomerTicketByOrderNumber, which gets the CustomerTicket based on OrderNumber.

Based on the above CustomerRepository, we can write a test case like this:

@ RunWith (SpringRunner.class) @ DataJpaTestpublic class CustomerRepositoryTest {@ Autowired private TestEntityManager entityManager; @ Autowired private CustomerTicketRepository customerTicketRepository; @ Testpublic void testFindCustomerTicketById () throws Exception {this.entityManager.persist (new CustomerTicket (1L, "Order00001", "DemoCustomerTicket1", new Date ()); CustomerTicket customerTicket = this.customerTicketRepository.getOne (1L); assertThat (customerTicket). IsNotNull () AssertThat (customerTicket.getId ()) .isEqualTo (1L);} @ Test public void testFindCustomerTicketByOrderNumber () throws Exception {String orderNumber = "Order00001"; this.entityManager.persist (new CustomerTicket (1L, orderNumber, "DemoCustomerTicket1", new Date ()); this.entityManager.persist (new CustomerTicket (2L, orderNumber, "DemoCustomerTicket2", new Date () List customerTickets = this.customerTicketRepository.getCustomerTicketByOrderNumber (orderNumber); assertThat (customerTickets). Size (). IsEqualTo (2); CustomerTicket actual = customerTickets.get (0); assertThat (actual.getOrderNumber ()) .isEqualTo (orderNumber);} @ Test public void testFindCustomerTicketByNonExistedOrderNumber () throws Exception {this.entityManager.persist (new CustomerTicket (1L, "Order00001", "DemoCustomerTicket1", new Date () This.entityManager.persist (new CustomerTicket (2L, "Order00002", "DemoCustomerTicket2", new Date ()); List customerTickets = this.customerTicketRepository.getCustomerTicketByOrderNumber ("Order00003"); assertThat (customerTickets). Size (). IsEqualTo (0);}}

As you can see here, we use @ DataJpaTest to implement CustomerRepository injection. At the same time, we also note that another core test component, TestEntityManager, is equivalent to the persistence of data without using real CustomerRepository, thus providing a mechanism for isolating data from the environment.

After executing these test cases, we need to pay attention to their console log input, where the core log is as follows (simplified for display):

Hibernate: drop table customer_ticket if existsHibernate: drop sequence if exists hibernate_sequenceHibernate: create sequence hibernate_sequence start with 1 increment by 1Hibernate: create table customer_ticket (id bigint not null, account_id bigint, create_time timestamp, description varchar, order_number varchar, primary key (id)) Hibernate: create table localaccount (id bigint not null, account_code varchar, account_name varchar, primary key (id))... Hibernate: call next value for hibernate_sequenceHibernate: call next value for hibernate_sequenceHibernate: insert into customer_ticket (account_id, create_time, description, order_number, id) values (?) Hibernate: insert into customer_ticket (account_id, create_time, description, order_number, id) values (?,?) Hibernate: select customerti0_.id as id1_0_, customerti0_.account_id as account_2_0_ Customerti0_.create_time as create_t3_0_, customerti0_.description as descript4_0_, customerti0_.order_number as order_nu5_0_ from customer_ticket customerti0_ where customerti0_.order_number=?... Hibernate: drop table customer_ticket if existsHibernate: drop sequence if exists hibernate_sequenceService layer and Controller testing

Unlike the underlying data access layer, the components of both layers depend on its next layer, that is, the Service layer depends on the data access layer, while the Controller layer depends on the Service layer. Therefore, when testing these two layers, we will use different schemes and technologies.

Use Environment to test configuration information

In Spring Boot applications, the Service layer usually depends on the configuration file, so we also need to test the configuration information.

There are two testing schemes for configuration information, the first one depends on the physical configuration file, and the second one is to dynamically inject configuration information during testing.

The first test scenario is relatively simple. When adding configuration files in the src/test/resources directory, Spring Boot can read the configuration items in these configuration files and apply them to the test case.

Before introducing the specific implementation process, it is necessary to take a look at the Environment interface, which is defined as follows:

Public interface Environment extends PropertyResolver {String [] getActiveProfiles (); String [] getDefaultProfiles (); boolean acceptsProfiles (String...) Profiles);}

As we can see in the above code, the main function of the Environment interface is to handle Profile, and its parent interface PropertyResolver definition is shown in the following code:

Public interface PropertyResolver {boolean containsProperty (String key); String getProperty (String key); String getProperty (String key, String defaultValue); T getProperty (String key, Class targetType); T getProperty (String key, Class targetType, T defaultValue); String getRequiredProperty (String key) throws IllegalStateException; T getRequiredProperty (String key, Class targetType) throws IllegalStateException; String resolvePlaceholders (String text); String resolveRequiredPlaceholders (String text) throws IllegalArgumentException;}

Obviously, the role of PropertyResolver is to obtain configuration property values based on the Key of various configuration items.

Now, assume that the application.properties in the src/test/resources directory has the following configuration items:

Springcss.order.point = 10

Then, we can design the test case shown below.

@ RunWith (SpringRunner.class) @ SpringBootTestpublic class EnvironmentTests {@ Autowired public Environment environment; @ Testpublic void testEnvValue () {Assert.assertEquals (10, Integer.parseInt ("springcss.order.point");}}

Here we inject an Environment interface and call its getProperty method to get the configuration information in the test environment.

In addition to setting properties in the configuration file, we can also use the @ SpringBootTest annotation to specify property values for testing. The sample code is as follows:

@ RunWith (SpringRunner.class) @ SpringBootTest (properties = {"springcss.order.point = 10"}) public class EnvironmentTests {@ Autowired public Environment environment; @ Test public void testEnvValue () {Assert.assertEquals (10, Integer.parseInt (environment.getProperty ("springcss.order.point"));}} use Mock to test the Service layer

The Service layer depends on the data access layer. Therefore, when testing the Service layer, we also need to introduce a new technical system, that is, the widely used Mock mechanism.

Next, let's look at the basic concepts of the Mock mechanism.

Mock mechanism

Mock means simulation, which can be used to isolate systems, components, or classes.

In the process of testing, we usually focus on the function and behavior of the test object itself, while we rely on some of the test objects. only focus on the interaction between them and the test object (such as whether to call, when to call, the parameters of the call, the number and order of calls, and the results returned or exceptions that occur, etc.), do not pay attention to the specific details of how these dependent objects perform the call.

Therefore, the Mock mechanism is to use Mock objects to replace real dependent objects and simulate real scenarios to carry out testing work.

As you can see, formally, Mock is the behavior of Mock classes and defining Mock methods directly in the test code, which is usually put together with the Mock code. Therefore, the logic of the test code is easily reflected in the code of the test case.

Let's take a look at how to test the Service layer using Mock.

Use Mock

The SpringBootTest.WebEnvironment.MOCK option in the @ SpringBootTest annotation, which is used to load WebApplicationContext and provides a Servlet environment for Mock, the built-in Servlet container is not actually started. Next, let's demonstrate this testing method for the Service layer.

First, let's look at a simple scenario where the following CustomerTicketService class exists in customer-service:

@ Servicepublic class CustomerTicketService {@ Autowired private CustomerTicketRepository customerTicketRepository; public CustomerTicket getCustomerTicketById (Long id) {return customerTicketRepository.getOne (id);}... }

Here we can see that the above method simply completes the data query operation through CustomerTicketRepository.

Obviously, when testing the integration of the above CustomerTicketService, we also need to provide a CustomerTicketRepository dependency.

Next, let's demonstrate how to use the Mock mechanism to isolate CustomerTicketRepository with the following code.

@ RunWith (SpringRunner.class) @ SpringBootTest (webEnvironment = SpringBootTest.WebEnvironment.MOCK) public class CustomerServiceTests {@ MockBean private CustomerTicketRepository customerTicketRepository; @ Test public void testGetCustomerTicketById () throws Exception {Long id = 1L; Mockito.when (customerTicketRepository.getOne (id)) .thenReturn (new CustomerTicket (1L, 1L, "Order00001", "DemoCustomerTicket1", new Date ()); CustomerTicket actual = customerTicketService.getCustomerTicketById (id); assertThat (actual). IsNotNull () AssertThat (actual.getOrderNumber ()) .isEqualto ("Order00001");}}

First, we inject CustomerTicketRepository; through the @ MockBean annotation, and then we complete the Mock of the getCustomerTicketById () method in CustomerTicketRepository based on the when/thenReturn mechanism provided by the third-party Mock framework Mockito.

Of course, if you want to inject the real CustomerTicketRepository directly into the test case, you can use the SpringBootTest.WebEnvironment.RANDOM_PORT option in the @ SpringBootTest annotation, as shown in the sample code:

@ RunWith (SpringRunner.class) @ SpringBootTest (webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) public class CustomerServiceTests {@ Autowired private CustomerTicketRepository customerTicketRepository; @ Test public void testGetCustomerTicketById () throws Exception {Long id = 1L; CustomerTicket actual = customerTicketService.getCustomerTicketById (id); assertThat (actual). IsNotNull (); assertThat (actual.getOrderNumber ()) .isEqualTo ("Order00001");}}

After running the above code, the entire Spring Boot project will be launched on a random port, and the real target data will be obtained from the database for verification.

The example of the above integration test contains only the dependency on the Repository layer, and sometimes a Service may contain both Repository and other Service classes or components, so let's go back to the CustomerTicketService class as follows:

@ Servicepublic class CustomerTicketService {@ Autowired private OrderClient orderClient; private OrderMapper getRemoteOrderByOrderNumber (String orderNumber) {return orderClient.getOrderByOrderNumber (orderNumber);}... }

Here we can see that in this code, in addition to relying on CustomerTicketRepository, it also depends on OrderClient.

Note that the OrderClient in the above code is a remote implementation class that accesses order-service through RestTemplate in customer-service, and the code is as follows:

@ Componentpublic class OrderClient {@ Autowired RestTemplate restTemplate; public OrderMapper getOrderByOrderNumber (String orderNumber) {ResponseEntity restExchange = restTemplate.exchange ("http://localhost:8083/orders/{orderNumber}", HttpMethod.GET, null, OrderMapper.class, orderNumber); OrderMapper result = restExchange.getBody (); return result;}}

The CustomerTicketService class doesn't really care about the specific process of how remote access is implemented in OrderClient. Because for integration testing, it only focuses on the results returned by the method call, we will also use the Mock mechanism to isolate the OrderClient.

The test case code for this part of CustomerTicketService is shown below, and you can see that we are testing in the same way.

Testpublic void testGenerateCustomerTicket () throws Exception {Long accountId = 100L; String orderNumber = "Order00001"; Mockito.when (this.orderClient.getOrderByOrderNumber ("Order00001")) .thenReturn (new OrderMapper (1L, orderNumber, "deliveryAddress")); Mockito.when (this.localAccountRepository.getOne (accountId)) .thenReturn (new LocalAccount (100L, "accountCode", "accountName")); CustomerTicket actual = customerTicketService.generateCustomerTicket (accountId, orderNumber) AssertThat (actual.getOrderNumber ()) .isEqualto (orderNumber);}

The test cases provided here demonstrate the various means of integration testing in the Service layer, which can already meet the needs of general scenarios.

Test the Controller layer

Before testing the Controller layer, let's provide a typical Controller class from customer-service, as shown in the following code:

@ RestController@RequestMapping (value= "customers") public class CustomerController {@ Autowired private CustomerTicketService customerTicketService; @ PostMapping (value= "/ {accountId} / {orderNumber}") public CustomerTicket generateCustomerTicket (@ PathVariable ("accountId") Long accountId, @ PathVariable ("orderNumber") String orderNumber) {CustomerTicket customerTicket = customerTicketService.generateCustomerTicket (accountId, orderNumber); return customerTicket;}}

The testing methods for the above Controller classes are relatively rich, such as TestRestTemplate, @ WebMvcTest annotations and MockMvc. Let's explain them one by one.

Use TestRestTemplate

The TestRestTemplate provided by Spring Boot is very similar to RestTemplate, except that it is specifically used in a test environment.

If we want to use @ SpringBootTest in the test environment, we can directly use TestRestTemplate to test the remote access process, as shown in the sample code:

@ RunWith (SpringRunner.class) @ SpringBootTest (webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) public class CustomerController2Tests {@ Autowired private TestRestTemplate testRestTemplate; @ MockBean private CustomerTicketService customerTicketService; @ Test public void testGenerateCustomerTicket () throws Exception {Long accountId = 100L; String orderNumber = "Order00001"; given (this.customerTicketService.generateCustomerTicket (accountId, orderNumber)) .willReturn (new CustomerTicket (1L, accountId, orderNumber, "DemoCustomerTicket1", new Date () CustomerTicket actual = testRestTemplate.postForObject ("/ customers/" + accountId+ "/" + orderNumber, null, CustomerTicket.class); assertThat (actual.getOrderNumber ()) .isEqualTo (orderNumber);}}

In the above test code, first, we notice that the @ SpringBootTest annotation specifies the Web runtime environment for random ports by using SpringBootTest.WebEnvironment.RANDOM_PORT. Then we initiate a HTTP request based on TestRestTemplate and verify the result.

Special note: the way to initiate a request using TestRestTemplate here is exactly the same as that of RestTemplate

Use @ WebMvcTest annotations

Next in the test method, we will introduce a new annotation @ WebMvcTest, which initializes the Spring MVC infrastructure necessary to test Controller. The test case for the CustomerController class is as follows:

@ RunWith (SpringRunner.class) @ WebMvcTest (CustomerController.class) public class CustomerControllerTestsWithMockMvc {@ Autowired private MockMvc mvc; @ MockBean private CustomerTicketService customerTicketService; @ Test public void testGenerateCustomerTicket () throws Exception {Long accountId = 100L; String orderNumber = "Order00001"; given (this.customerTicketService.generateCustomerTicket (accountId, orderNumber)) .willReturn (new CustomerTicket (1L, 100L, "Order00001", "DemoCustomerTicket1", new Date () This.mvc.perform (post ("/ customers/" + accountId+ "/" + orderNumber) .accept (MediaType.APPLICATION_JSON)) .andexpect (status (). IsOk ());}}

The basic methods provided by the MockMvc class are divided into the following six types, which correspond to each other below.

Perform: executes a RequestBuilder request, which automatically executes the SpringMVC process and maps to the corresponding Controller for processing.

Get/post/put/delete: declares how to send a HTTP request, obtains a HTTP request based on the URI template and the value of the URI variable, and supports HTTP methods such as GET, POST, PUT, DELETE, and so on.

Param: add request parameters, which will not be used when sending JSON data, but should be annotated with @ ResponseBody.

AndExpect: add a ResultMatcher verification rule to verify whether the Controller execution result is correct by judging the returned data.

AndDo: add ResultHandler result handlers, such as printing results to the console when debugging.

AndReturn: finally, return the corresponding MvcResult, and then perform custom validation or do asynchronous processing.

After executing the test case, it is not difficult to see from the output console log that the whole process is equivalent to starting CustomerController and performing remote access, while the CustomerTicketService used in CustomerController is Mock.

Obviously, the purpose of testing CustomerController is to verify the format and content of the data it returns. In the above code, we first define the JSON result that CustomerController will return, then simulate the whole process of HTTP request by perform, accept and andExpect methods, and finally verify the correctness of the result.

Please note that the @ SpringBootTest annotation cannot be used with the @ WebMvcTest annotation.

Use @ AutoConfigureMockMvc annotations

In the scenario where the @ SpringBootTest annotation is used, if we want to use the MockMvc object, we can introduce the @ AutoConfigureMockMvc annotation.

By combining the @ SpringBootTest annotation with the @ AutoConfigureMockMvc annotation, the @ AutoConfigureMockMvc annotation will automatically configure the MockMvc class in the Spring context loaded by @ SpringBootTest.

The test code using the @ AutoConfigureMockMvc annotation is as follows:

@ RunWith (SpringRunner.class) @ SpringBootTest@AutoConfigureMockMvcpublic class CustomerControllerTestsWithAutoConfigureMockMvc {@ Autowired private MockMvc mvc; @ MockBean private CustomerTicketService customerTicketService; @ Test public void testGenerateCustomerTicket () throws Exception {Long accountId = 100L; String orderNumber = "Order00001"; given (this.customerTicketService.generateCustomerTicket (accountId, orderNumber)) .willReturn (new CustomerTicket (1L, 100L, "Order00001", "DemoCustomerTicket1", new Date () This.mvc.perform (post ("/ customers/" + accountId+ "/" + orderNumber) .accept (MediaType.APPLICATION_JSON)) .andexpect (status (). IsOk ());}}

In the above code, we use the MockMvc utility class to complete the simulation of the HTTP request and verify the correctness of the Controller layer components based on the return status.

This is the end of the content of "what is the implementation of SpringBoot application testing?" Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report