Junit+mockito combining Test Spring MVC Controller

Source: Internet
Author: User

[This article is from the Sky Cloud-owned blog Park]

Brief description

Using JUnit combined with Mockito, coupled with some of the Spingframework's own methods, can be combined to test the controller layer in spring MVC.

Before we design the test case, we have to take the logic of the controller's code in-depth and go through the drill-by-layer. The purpose of the walk-through is to identify the main logical branches of the controller in order to design test cases for coverage. Some of the major common concerns are:

1. Request the parameter values contained in requests (parameters obtained from the request in the controller)

2. Method calls in a try block in a controller that can cause an exception

3. Variable values involved in the IF statement in the controller

4. Some threadlocal methods (the Threadlocal object needs to be manipulated during the actual test to simulate some states)

Test specification

Create a backend test branch: it must be created on the basis of the development Branch, and it is convenient to debug the test code by modifying the development code.

To create a test class: test class name B with the class name A to be tested the relationship is B=atest

Add comment on test class: @RunWith (Mockitojunitrunner.class)

The test class declares: Private Mockmvc Mockmvc;

Note on the Controller declaration for the service mock to be injected in the test class: @InjectMocks

Comment on the service declaration to be Mock in the test class: @Mock

Comment on the test method: @Test

Common references (if the IDE does not automatically download the corresponding Maven repositories, you need to manually modify the Pom.xml file to add references to the appropriate MAVEN repositories):

ImportOrg.junit.Before;Importorg.junit.Test;ImportOrg.junit.runner.JUnitCore;ImportOrg.junit.runner.Result;ImportOrg.junit.runner.RunWith;Importorg.junit.runner.notification.Failure;Importorg.mockito.InjectMocks;ImportOrg.mockito.Mock;Importorg.mockito.MockitoAnnotations;ImportOrg.mockito.runners.MockitoJUnitRunner;ImportORG.SPRINGFRAMEWORK.TEST.WEB.SERVLET.MOCKMVC;ImportOrg.springframework.test.web.servlet.RequestBuilder;Importorg.springframework.test.web.servlet.request.MockMvcRequestBuilders;Importorg.springframework.test.web.servlet.setup.MockMvcBuilders;Import StaticOrg.mockito.Matchers.any;Import Staticorg.mockito.Matchers.anyString;Import StaticOrg.mockito.Mockito.doReturn;Import StaticOrg.mockito.Mockito.doThrow;Import StaticOrg.springframework.test.web.servlet.result.MockMvcResultHandlers.print;Import StaticOrg.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;

Standard examples of initialization methods:

@Before  Public void throws Exception {    mockitoannotations.initmocks (this);     this. Mockmvc = Mockmvcbuilders.standalonesetup (declared controller). build ();}

Example of standard structure for test methods:

@Test  Public void throws Exception {    //  custom fill     /  mock dependency     //  construct request     // execute request and assertion }

Examples of filling methods for environmental threadlocal:

// Fill is empty XXThreadLocalContainer.XXX_THREAD_LOCAL.set (null); // fills the specified type Object New A (); A.setxx ("test"); XXThreadLocalContainer.XXX_THREAD_LOCAL.set (a);

Examples of mock methods that have no return service method Dependency Injection:

Dothrow (Exception.  Class). When (Someservice). Dosomemethod (Any (Someclassa.  Class), any (SOMECLASSB.  Class), AnyString (), anystring (), any (someenum.  Class));

Examples of mock methods that have a return service method dependency Injection:

// constructs the object returned by the mock method New A (); A.setsomepropertya (Somevaluea); A.setsomepropertyb (SOMEVALUEB) ; // constructs a mock method Doreturn (a). When (Someservice). Dosomemethod (AnyString (), anystring ());

Use Requestbuilder to construct a GET request example:

Requestbuilder request = Mockmvcrequestbuilders.get (Someurl). Requestattr ("Someattrnamea", Somevaluea). RequestAttr ( "Someattrnameb", Somevalueb). Requestattr ("Someattrnamec", SOMEVALUEC);

Examples of execution requests and assertions:

Mockmvc.perform (Request). Anddo (print ()). Andexpect (JsonPath ("Somefieldname"). Value (String.valueof ( (Somefieldvalue)));

Customize the main function to perform the test:

 Public Static void Main (string[] args) {    = junitcore.runclasses (mpresurrectioncontrollertest.  Class);      for (Failure failure:result.getFailures ()) {        System.out.println (String.Format ("FAILED:%s", Failure.tostring ()));    }    System.out.println (String.Format ("TEST SUCCESS:%s",    result.wassuccessful ()));}

Junit+mockito combining Test Spring MVC Controller

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.