MVC+WEBAPI Unit Test

Source: Internet
Author: User

1. Preface

Now that the project has a phased module, we want to unit test these modules to ensure the quality of the code of the project. First, although the title is Mvc+webapi essentially I'm just testing mvc. When using the VS Unit Test generator. As for its installation and introduction in this does not do a detailed introduction. OK now start summarizing my unit test summary.

2. Unit Test Build 2.1 new unit test project

This project I was to treat it as a module plugin.

2.2. Adding unit Test classes

[TestClass] Public classMtnfim {//instantiate a test MVC ControllerMgtcontroller Mtn_fim =NewMgtcontroller (); [TestMethod] Public voidindextest () {//calling a method in a class            varret = Mtn_fim. Index () asViewResult; intErrcode =Testresult.action_result (ret). Errcode; Assert.AreEqual (0, Errcode); }}
View Code2.3. The code is interpreted as follows:2.3.1Assertuse of the class

Assert.AreEqual () tests whether the specified values are equal, and if so, the test passes;

Aresame () is used to verify that the specified two object variables are pointing to the same object, otherwise it is considered an error

Arenotsame () is used to verify that the specified two object variables are pointing to different objects, otherwise it is considered an error

Assert.istrue () tests if the specified condition is true, and if true, the test passes;

Assert.isfalse () tests whether the specified condition is false and if false, the test passes;

Assert.isnull () tests whether the specified object is a null reference, and if it is empty, the test passes;

Assert.isnotnull () tests whether the specified object is non-null, and if not NULL, the test passes;

     2.3.2. Handling of return types

The return type of MVC controller in my project has two jsonresult. Actionrresult. Two, so the use of the Assert class is obviously something I want to do with the returned object of MVC.

How to handle Jsonresult:

Download the exposedobject from Nugt to Dynami and manipulate the object. The code is as follows.

var jsonret = Mtn_fim.add_feeitem (" test ""cs");             var ret = exposed.from (jsonret. Data);             int errcode = ret.errcode;            Assert.AreEqual (6002, Errcode);
View Code

Treatment of Actionrresult :

Relative to the Jsonresult direct operation returns the object, I wrote a method for this.

  Public Static classTestResult { Public Staticresult<Object>Action_result (ViewResult ret) {return((wx.web.result<Object>) ((( System.Web.Mvc.ViewResultBase) ((ret))).        Model)); }         Public Staticresult Apicitroller_result (System.Web.Http.IHttpActionResult action) {varrs = ((system.web.http.results.oknegotiatedcontentresult<wx.web.result>(Action)).            Content; returnrs; }    }
View Code

Use the following:

var  as ViewResult;             int Errcode = testresult.action_result (ret). Errcode;            Assert.AreEqual (0, Errcode);
View Code

3. Beyond the realization:

3.1. Database initialization

The basic implementation of unit testing has been achieved initially, but given the repeated testing of unit tests, I use the EF code First dynamic database creation and the data that needs to be tested.

  Public voidInitialize (Feedbcontext context) {List<organization> orgs =NewList<organization>() {                 NewOrganization () {oid=1, name="New Sino-New Group 1", state=true, reg_time=DateTime.Now},NewOrganization () {oid=2, name="Shandong University", state=true, reg_time=DateTime.Now},NewOrganization () {oid=3, name="Zhejiang University", state=true, reg_time=DateTime.Now},NewOrganization () {oid=4, name="Tongji University", state=true, reg_time=DateTime.Now}}; List<fee_item> FIM =NewList<fee_item>() {                 NewFee_item () {name="Electricity", code="POW", Type= feeitemtype.normal,state=true, icon="Img/jf_dianf.png", sort=0, appid=0, reg_time=DateTime.Now},NewFee_item () {name="Net fee", code="Net", Type= feeitemtype.normal,state=true, icon="Img/jf_wangf.png", sort=1, appid=1, reg_time=DateTime.Now},NewFee_item () {name="level 46", code="CET", Type= feeitemtype.normal,state=true, icon="Img/jf_siliuj.png", sort=2, appid=2, reg_time=DateTime.Now},NewFee_item () {name="Registration Fee", code="POW", Type= feeitemtype.normal,state=true, icon="Img/jf_baomingf.png", sort=3, appid=3, reg_time=DateTime.Now},NewFee_item () {name="Insurance Premiums", code="POW", Type= feeitemtype.normal,state=false, icon="Img/jf_baox.png", sort=4, appid=4, reg_time=DateTime.Now},NewFee_item () {name="Accommodation fee", code="POW", Type= feeitemtype.normal,state=true, icon="Img/jf_dianf.png", sort=5, appid=5, reg_time=DateTime.Now}}; List<school_power> Con_power =NewList<school_power>() {             NewSchool_power () {oid=1, power_code="Ykt", power_id="1", reg_time=DateTime.Now},NewSchool_power () {oid=1, power_code="Sims", power_id="2", reg_time=DateTime.Now}}; //depts. ForEach (o = Context.dept.Add (o));Orgs. ForEach (o =context.organization.Add (o)); Fim. ForEach (o=Context.fee_item.            ADD (o)); Con_power. ForEach (o=Context.control_power.            ADD (o)); Context.        SaveChanges (); }
View Code
    Public voidInitial () {Try            {                varContext =NewFeedbcontext (); if(context. Database.exists ()) {context.                Database.delete (); }                NewList<idatainitializer<feedbcontext>>() {                         Newdatainit4dept ()}. Setup<FeeDbContext>(context); }            Catch(Dbentityvalidationexception ex) {StringBuilder error=NewStringBuilder (); foreach(varIteminchEx. entityvalidationerrors) {foreach(varItem2inchitem. validationerrors) {error. Append (string. Format ("{0}:{1}\r\n", item2. PropertyName, Item2.                    errormessage)); }} Console.WriteLine ("Database initialization error:"+error); Throwex; }            Catch(Exception e) {Console.WriteLine ("Database initialization error:"+e.message); Throwe; }        }
View Code

After the EF code first is written, it goes back to the Unit test section, so it is necessary to use the attached properties of the unit tests to execute each unit test content each time it executes:

[ClassInitialize ()] Run code before running the first test of a class

[ClassCleanup ()] Run code after all tests in the class are run

[TestInitialize ()] Run the code before running each test

[TestCleanup ()] Run code after each test run

[ClassInitialize]          Public Static void Initialdb (TestContext context)        {            // Initialize database             New Databuilder (). initial ();             // load Webapi bin file             apiconfig_factory. Instance.load_apis ();        }
View Code

Until this unit test implementation is finished, but for unit testing there are many things not to write, such as test model, coverage, and so on, the test for this project is not limited to unit testing, behind the performance test and UI testing will take time to summarize.

  

Mvc+webapi Unit tests

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.