Vs2013 unit test (use the unit test provided by vs2013)

Source: Internet
Author: User

This document is the learning notes of the official documents.

1. Open vs3013 and create a solution, for example, unittest. Create a class library project unittest_bank. Add a bankaccount class to this project, the methods in this class and class are the objects to be tested.

2. Add a test project to unittest: Right-click solution name = add = new project = Visual C # = test = unit test project. The project name is unittest_banktest, add unittest_bank as the reference project of unittest_banktest, and rename the default class generated in the test project unittest_banktest to bankaccounttest.

For the bankaccounttest class, testclass is annotated on the class, and testmethod is annotated on the method. You can add other classes and methods to these files for testing.

First test:

3. Now we test the debit method of the bankaccount class. We determine in advance that the test should check the following aspects:

A. If the credit balance is greater than the account balance, this method throws an exception argumentoutofrangeexception.

B. If the credit balance is less than 0, an exception is thrown.

C. If both A and B meet the requirements, this method will subtract amount (function parameter) from the account balance)

Note: the last line of the debit method in the mail bankaccount class should be-=, rather than + =. Of course, this is a deliberate bug, instead of Microsoft's mistakes, we are waiting to test it in this test and correct it.

  

Add the following method to the test class to test the debit method:

// unit test code[TestMethod]public void Debit_WithValidAmount_UpdatesBalance(){    // arrange    double beginningBalance = 11.99;    double debitAmount = 4.55;    double expected = 7.44;    BankAccount account = new BankAccount("Mr. Bryan Walton", beginningBalance);    // act    account.Debit(debitAmount);    // assert    double actual = account.Balance;    Assert.AreEqual(expected, actual, 0.001, "Account not debited correctly");}

 

  

Test method requirements:

The testmethod annotation must be provided. The return type is void and no parameter is allowed.

After testing, we found a bug and changed + = to-=.

Use unit test to improve code:

The test is still debit. The purpose of this test is to complete the following:

A. If the credit amount (which should be debit amount) is larger than the balance, the method will throw argumentoutofrangeexception

B. If the credit amount is smaller than 0, an argumentoutofrangeexception is thrown.

(1) create a test method

Try to create a test method for the first time to solve the above problem:

Code:

//unit test method[TestMethod][ExpectedException(typeof(ArgumentOutOfRangeException))]public void Debit_WhenAmountIsLessThanZero_ShouldThrowArgumentOutOfRange(){    // arrange    double beginningBalance = 11.99;    double debitAmount = -100.00;    BankAccount account = new BankAccount("Mr. Bryan Walton", beginningBalance);    // act    account.Debit(debitAmount);    // assert is handled by ExpectedException}

 

Note: When debit amount is less than 0, this test should cause the tested method to throw an argumentoutofrange exception. Otherwise, this test will fail and fail to meet expectations, debit code needs to be modified to fulfill this test expectation-TDD development.

We use the expectedexceptionattribute feature to assert that the expected exception should be thrown. Unless the method throws an argumentoutofrangeexception, this feature will cause the test to fail (note the intention of this test ). Run the test with positive and negative debitamount, and modify the debit method temporarily: An applicatinexception is thrown when the demit amount is less than 0. After all these tasks, we found that this test was basically normal.

To test whether debit amount is greater than balance, we perform the following operations:

A. Create a new test method named debit_whenamountismorethanbalance_shouldthrowargumentoutofrange.

B. Previous test method

Debit_whenamountislessthanzero_shouldthrowargumentoutofrange

Copy the method body to this test method

C. Set debitamount to a value greater than balance.

(2) Running Test Method

Run debit_whenamountismorethanbalance_shouldthrowargumentoutofrange with different debitamount values

And debit_whenamountislessthanzero_shouldthrowargumentoutofrange

Then run three tests so that all the three cases we set at the beginning are overwritten.

(3) Continue analysis

The next two testing methods are debit_whenamountismorethanbalance_shouldthrowargumentoutofrange.

And debit_whenamountislessthanzero_shouldthrowargumentoutofrange

Some problems: When two tests run, you don't know who throws the exception based on the expectedexception feature.

You can modify it as follows:

Define two constants in the class:

// class under testpublic const string DebitAmountExceedsBalanceMessage = "Debit amount exceeds balance";public const string DebitAmountLessThanZeroMessage = "Debit amount less than zero";// method under test// ...    if (amount > m_balance)    {        throw new ArgumentOutOfRangeException("amount", amount, DebitAmountExceedsBalanceMessage);    }    if (amount < 0)    {        throw new ArgumentOutOfRangeException("amount", amount, DebitAmountLessThanZeroMessage);    }// ...

 

(4) reconstruction test method

First, remove the expectedexception feature. Instead, we capture exceptions to verify under which conditions the throws are thrown.

Modify debit_whenamountismorethanbalance_shouldthrowargumentoutofrange.

Method:

[TestMethod]public void Debit_WhenAmountIsGreaterThanBalance_ShouldThrowArgumentOutOfRange(){    // arrange    double beginningBalance = 11.99;    double debitAmount = 20.0;    BankAccount account = new BankAccount("Mr. Bryan Walton", beginningBalance);    // act    try    {        account.Debit(debitAmount);    }    catch (ArgumentOutOfRangeException e)    {        // assert        StringAssert.Contains(e.Message, BankAccount. DebitAmountExceedsBalanceMessage);    }}

 

(5) test again, rewrite again, and analyze again

When we run the test method debit_whenamountismorethanbalance_shouldthrowargumentoutofrange again with no parameters

You may encounter the following problems:

1. If we run debitamount, which is larger than balance, the test results will be expected.

2. If a debitamount operation is used, it will make assert assertions fail (for example, an unexpected exception is returned in a line of the debit method, in the sense of this test.

3. What happens if debitamount is valid (greater than 0 and smaller than balance? If no exception is thrown, the assertion will not fail and the test method is passed. -- This is not what we want. Pay attention to the original intention of this test: either the assertions are successful or the assertions fail. If we cannot enter the asserted code, we can only explain the problem of writing the test method!

To solve this problem, we add a fail assertion in the last line of the test method to handle the case where no exception occurred: no exception occurred, which means that this test did not meet expectations!

But after the modification is run again, you will find that if the expected exception is caught, the test will always fail. To solve this problem, we add a return before stringassert.

Our final debit_whenamountismorethanbalance_shouldthrowargumentoutofrange

The method is as follows:

[TestMethod]public void Debit_WhenAmountIsGreaterThanBalance_ShouldThrowArgumentOutOfRange(){    // arrange    double beginningBalance = 11.99;    double debitAmount = 20.0;    BankAccount account = new BankAccount("Mr. Bryan Walton", beginningBalance);    // act    try    {        account.Debit(debitAmount);    }    catch (ArgumentOutOfRangeException e)    {        // assert        StringAssert.Contains(e.Message, BankAccount. DebitAmountExceedsBalanceMessage);        return;    }    Assert.Fail("No exception was thrown.")}

 

In the end, we make the test code more robust, but more importantly, in this process, we also improved the tested code-this is the ultimate purpose of the test.

 

Microsoft will talk about test-driven development. The link is as follows:

Test-driven development

 

Source code: unittest.rar

Vs2013 unit test (use the unit test provided by vs2013)

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.