Springboot Project Unit Testing

Source: Internet
Author: User

Some time ago, a friend asked Springboot how to use unit testing, combined with the actual use of LZ company, here to describe the three kinds of unit testing methods.

1. Conventions

The unit test code is written in the Src/test/java directory
The Unit test class is named *test, prefixed with the class name to be tested

2. Unit test using mock mode

The Spring test Framework provides MOCKMVC objects that can be tested in MVC without the need for client-server requests, and can execute the controller's request completely on the server side, just as it does with the test servers.
The test environment needs to be established before the test starts, and the Setup method is @before modified. Use the Mockmvcbuilders tool to create a Mockmvc object using the Webapplicationcontext object as a parameter.

  @RunWith (Springrunner.class) @SpringBootTest (classes = application.class)// The application here is Springboot's startup class name @webappconfigurationpublic class Stylecontrollertest {@Autowired private Webapplicati    Oncontext context;    Private MOCKMVC Mockmvc;    Private Objectmapper mapper = new Objectmapper (); @Before public void Setupmockmvc () throws Exception {Mockmvc = Mockmvcbuilders.webappcontextsetup (context). Buil    D ();        } @Test public void Testsend () throws Exception {Long ID =1l; Invokes the interface, passing in the added user parameter Mockmvc.perform (mockmvcrequestbuilders.get ("/style/liststylebyid"). ContentType (Med IATYPE.APPLICATION_JSON_UTF8). Content (mapper.writevalueasstring (ID))). Andexpect (Mockmvcres Ultmatchers.status (). IsOk ()). Andexpect (Mockmvcresultmatchers.content (). ContentType (Mediatype.application_j    Son_utf8). Anddo (Mockmvcresulthandlers.print ()); }}
3. Using Feign Mode Unit test

The following is a sample unit test for the feign interface, starting the project, testing the service provided by this jar, not starting the service, changing to a remote service address, and testing the services provided by the remote Jar
which

@EnableFeignClients(clients = UserControllerTest.UserServiceFeignClient.class)

Similar to our actual application invocation of related services.

@RunWith(SpringJUnit4ClassRunner.class)@SpringBootTest(classes = UserControllerTest.class)@Import({ FeignAutoConfiguration.class, HttpMessageConvertersAutoConfiguration.class })@EnableFeignClients(clients = UserControllerTest.UserServiceFeignClient.class)public class UserControllerTest {    @FeignClient(value = "loan-server", url = "http://localhost:9070/")    public interface UserServiceFeignClient extends UserServiceClient {    }    @Autowired    private UserServiceFeignClient userServiceFeignClient;    @Test    public void getUser() {        User user = userServiceFeignClient.getSDKUserById(1);        System.out.println(user);    }}
4. Using the HTTP Rest API Unit test

Use Resttemplate to initiate a GET or POST request where @springboottest the two lines comment out without launching the Springboot container for direct remote call testing

@RunWith(SpringJUnit4ClassRunner.class)public class LoanControllerTest {    private  final  static String url =  "http://localhost:9070/";    private static RestTemplate restTemplate = new RestTemplate();    @Test    public void test(){        ResponseEntity<String> response = restTemplate.exchange(url + "/loan/getLoanById?id=1" ,                HttpMethod.GET,                new HttpEntity(null),                String.class);        System.out.println("result: " + response.getBody());    }}

Welcome to sweep the code to pay attention to my public number, with you to share the technology and growth of the story.

Springboot Project Unit Testing

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.