Unit test for Spring boot

Source: Internet
Author: User

I've recently done some spring boot unit testing, to summarize.


Unit testing as much as possible with the spring boot framework to reduce coupling, when you are testing a function point is a need to mock too many objects, you should realize that this function point coupling is too high


Use constructor injection, do not use field injection. This makes it easier to write unit test code. After the spring Framework 4.3, if you have only one constructor, you no longer need to write @autowired,spring will default he is the Autowire target:

public class Orderentryserviceimpl implements Orderentryservice {private Orderentryrepository orderentryrepository    ;    Public Orderentryserviceimpl (Orderentryrepository repository) {orderentryrepository=repository; }}

This makes it easy to initialize the object in a unit test.

public class orderentryservicetest {     @MockBean      private orderentryrepository orderentryrepository;    private  orderentryservice service;     @Before     public void  SetUp ()     {        orderentryrepository= Mockito.mock (Orderentryrepository.class);        service=new  Orderentryserviceimpl (orderentryrepository);    }    private  Orderentry orderentry=new orderentry ();     @Test     public  void findbyidtest ()     {         Mockito.when (Orderentryrepository.findone (Mockito.anylong ())). Thenreturn (OrderEntry);         orderentry entry=service.FindByID (New long (1));         assertequals (Entry.getId (), Orderentry.getid ());    }     @Test     public  Void updateentrytest ()  throws Exception    {         final string orderentryjson = ioutils.tostring (This.getClass (). getResourceAsStream ("/static/meta-data/orderentry-example.json"),                 CharEncoding.UTF_8         );        objectmapper mapper=  Objectmapperfactory.getinstance ();                 mockito.when (Orderentryrepository.getone (Mockito.anylong ())). ThenReturn (OrderEntry);         mockito.Doanswer (Returnsfirstarg ()). When (Orderentryrepository). Save (Mockito.any (Orderentry.class));         orderentry entry =service.update (New long (1), Mapper.readTree ( Orderjson));         assertequals (New long (2), entry.getQuantity ()) ;         assertequals (New double (Ten), Entry.getUnitPrice ());     }}


To test spring Repository, we can use @datajpatest so that we can use Testentitymanager to test our Repository functionality.

@RunWith (springrunner.class) @DataJpaTestpublic class Clientrepositorytest {@Autowired private Testentitymanager ent        Itymanager;        @Autowired private Clientrepository clientrepository;        @Test public void Testfindbyname () {entitymanager.persist (New Client ("Wang"));        optional<client> Client = Clientrepository.findbyname ("Wang");    Assertequals ("Wang", Client.get (). GetName ()); }}

To test the serialization and deserialization of JSON, you need to use @jsontest

@RunWith (springrunner.class) @JsonTestpublic class Customerjsontests {private jacksontester<customer> json;        @Test public void Serializejson () {Customer customer= New customer ("Wang");    Assertthat (This.json.write (Details)). Extractingjsonpathstringvalue ("@.name"). Isequalto ("Wang"); }}


To test the spring MVC Controller, you need to use the @webmvctest

@Autowiredprivate  MockMvc mockMvc; @MockBeanprivate  orderentryservice orderentryservice;@ Testpublic void updateorderentrybyidtest ()  throws exception{    final  string orderentryjson = ioutils.tostring (This.getclass (). getResourceAsStream ("/static/ Meta-data/orderentry-example.json "),             charencoding.utf_8    );     mockito.when (OrderEntryService.findById ( Mockito.anylong ())). Thenreturn (Entry);    requestbuilder requestbuilder =  Mockmvcrequestbuilders.patch ("/ORDERENTRIES/1"). Accept (             mediatype.application_json)              .contenttype (ContentType)             . Content (Orderentryjson); &nbSp;   mvcresult result= mockmvc.perform (Requestbuilder). AndReturn ();     assertequals (HttpStatus.ACCEPTED.value (), Result.getresponse (). GetStatus ());


This article is from the "Handy Notes" blog, so be sure to keep this source http://wangjiong.blog.51cto.com/10810468/1922584

Unit test for Spring boot

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.