Use of test code for Windows 8 Development

Source: Internet
Author: User

1. Create a solution and unit test project
1) Select "new" from the "file" menu, and then select "new project ".
2) In the "new project" dialog box, expand "installed", "Visual C #", and select "Windows Store ". Select "Blank application" from the Project template list ".
3) Name the project mytestproject and ensure that the "directory for creating the solution" is selected ".
4) In Solution Explorer, select solution name, select "add" from the shortcut menu, and then select "new project ".
5) in the "New Project" dialog box, expand "installed" and "Visual C #", and then select "Windows App Store ". Select "Unit Test Library (Windows Store application)" from the Project template list )".

Note: Create a project first, and then add a test project to the project. This meets our needs for testing our project during development.

6) Open unittest1.cs in the Visual Studio editor.

namespace UnitTestLibraryTest{    [TestClass]    public class UnitTest1    {            [TestMethod]        public void TestMethod1()        {        }    }}

Note the following:

A. Each test is defined using [testmethod. The test method must return void and cannot have any parameters. Add the [testclass] statement to the first line of the class name.

B. the test method must be located in the class modified using the [testmethod] feature. During the test, an instance is created for each test class. The test method will be called in the unspecified order.

C. You can define the specific methods that are called before and after each module, class, or method.

D. Add using Microsoft. visualstudio. testplatform. unittestframework; to the file header.

7). initialize and clean up before the test. The usage and Code are as follows:

Namespace unittestlibrarytest {[testclass] public class unittest1 {private int A; private int B; // run the first test method before the current test class runs, similar to the constructor [classinitialize] public static void myclassinit (testcontext context) {}// run after all test methods are completed, similar to the Destructor [classcleanup] public static void myclassend () {}// run [testinitialize] public void Init () {A = 1; B = 1 ;} // after each test method is run, run [testcleanup] public void end () {A = 0; B = 0 ;}}}

Note: The above method can be customized with no return value. Except that the function of [classinitialize] has a testcontext parameter, there are no other parameters.

2. verify whether the test is run in the test Manager.

1). insert some test code in testmethod1 of the unittest1.cs file:

        [TestMethod]        public void AddTestMethod()        {            int a = 1;            int b = 2;            int sum = a+b;            Assert.AreEqual(3,sum);        }

Note that several static methods provided by the assert class can be used to verify the results of the test method.

2) on the "test" menu, select "run" and select "Run all ".
The test project is generated and run. The "test resource manager" window is displayed, and the test is listed under "tested. The summary pane at the bottom of the window provides additional details about the selected test.

  

3. Add a rooter class to the mytestproject Project

1) In Solution Explorer, select the project name "mytestproject. Select "add" from the shortcut menu and select "class ".
2) Name the class file as "Rooter. cs.
3) Add the following code to the rooter class. CS file:

    public class Rooter    {        public Rooter()        {         }        public double SquareRoot(double x)        {            return 0.0;        }    }

The rooter class declares a constructor and the sqareroot estimator method.

4) The sqareroot method is only a minimum implementation, which is sufficient to set the basic structure for testing.

4. Merge test items into application projects 

1) Add a reference to the "mytestproject" application to the unittestlibrarytest project.

2). Add the using statement to the unittest1.cs file:

A. Open unittest1.cs.

B. Add the code using mytestproject IN THE using Microsoft. visualstudio. testplatform. unittestframework; line;

3) Add a test using the rooter function. Add the following code to unittest1.cs:

        [TestMethod]        public void BasicTest()        {            Rooter rooter = new Rooter();            double expected = 0.0;            double actual = rooter.SquareRoot(expected * expected);            double tolerance = .001;            Assert.AreEqual(expected, actual, tolerance);        }

4). Generate a solution.

The new test is displayed in the "test not running" node of the test resource manager.

5) in the test resource manager, select "Run all ". Passed the basic test

You have set up a test and code project and verified that you can run a function test in the Code project. Now you can start writing real tests and code.

5. Add tests in iterative mode and make them pass.

1). Add a new test:

        [TestMethod]        public void RangeTest()        {            Rooter rooter = new Rooter();            for (double v = 1e-6; v < 1e6; v = v * 3.2)            {                double expected = v;                double actual = rooter.SquareRoot(v * v);                double tolerance = ToleranceHelper(v);                Assert.AreEqual(expected, actual, tolerance);            }        }        private double ToleranceHelper(double expected)        {            return expected / 3.2;         }

Tip: We recommend that you do not change the passed tests. Instead, add a new test, update the code to pass the test, and then add other tests. When your users change their requirements, disable tests that are no longer correct. Write new tests and make them run one at a time in the same incremental mode.

2) In the test resource manager, select "Run all ".

3). The test will not pass. Rangetest failed

Tip: after writing a test, immediately verify that each test fails. This helps you avoid mistakes that are easy to make and won't write tests that never fail.

4). Enhance the tested code so that the new test passes. Change the sqareroot function in Rooter. CS:

        public double SquareRoot(double x)        {            double estimate = x;            double diff = x;            while (diff > estimate / 1000)            {                double previousEstimate = estimate;                estimate = estimate - (estimate * estimate - x) / (2 * estimate);                diff = Math.Abs(previousEstimate - estimate);            }            return estimate;        }

5) generate a solution, and then select "Run all" in the test resource manager ".

Now all three tests will pass.

Tip: one-time code development by adding a test. Make sure all tests pass after each iteration.

6. Call the failed test

1). Add another test to unittest1.cs:

        [TestMethod]        public void NegativeRangeTest()        {            string message;            Rooter rooter = new Rooter();            for (double v = -0.1; v > -3.0; v = v - 0.5)            {                try                {                    // Should raise an exception:                    double actual = rooter.SquareRoot(v);                    message = String.Format("No exception for input {0}", v);                    Assert.Fail(message);                }                catch (ArgumentOutOfRangeException ex)                {                    continue; // Correct exception.                }                catch (Exception e)                {                    message = String.Format("Incorrect exception for {0}", v);                    Assert.Fail(message);                }            }        }

2) In the test resource manager, select "Run all ".

The test will not pass. In the test resource manager, select a test name. The assertions of failure are highlighted. The failure message is visible in the details pane of the test resource manager. Negativerangetests failed.

3) To view the reason why the test fails, perform the following functions in one step:

A. Set a breakpoint at the beginning of the squareroot function.

B. Select "Debug selected test" from the shortcut menu that fails the test ". When running stops at the breakpoint, perform the following code in one step.

C. Add code to the rooter method to catch exceptions. Modify the squareroot method as follows (identify and catch exceptions for X ):

  

        public double SquareRoot(double x)        {            if (x < 0.0)            {                throw new ArgumentOutOfRangeException();            }            double estimate = x;            double diff = x;            while (diff > estimate / 1000)            {                double previousEstimate = estimate;                estimate = estimate - (estimate * estimate - x) / (2 * estimate);                diff = Math.Abs(previousEstimate - estimate);            }            return estimate;        }

In the test resource manager, select "Run all" to test the corrected method and ensure that regression testing is not introduced. All tests will pass.

 

Related Article

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.