Статьи

Настройка модульного тестирования в Windows Phone 7 и 8

Вступление

После прочтения комментариев к  этому видео  и на форумах, кажется, возникает много путаницы в том, как настроить «модульное тестирование» в Windows Phone 7 и 8. На самом деле это очень просто, и я покажу вам пошаговую инструкцию Как настроить первый тестовый модуль в Windows Phone 7 или 8.

Давайте начнем

Прежде чем начать  Visual Studio 2012, обновление 2, CTP 2  включает шаблон проекта для модульного тестирования. Единственным недостатком является то, что это относится только к WP8. Шаблон не будет отображаться, если у вас не установлен 8.0 SDK.

Если у вас уже есть проект Windows Phone 7 или 8, для которого вы хотите выполнить модульное тестирование, все, что вам нужно сделать, — это создать еще один проект Windows Phone 7 или 8 в том же решении, как показано ниже. Этот проект может быть стандартным шаблоном «Приложение для Windows Phone». Возможно, вы захотите дать ему значимое имя, такое как UnitTestWP8App и т. Д.

образ

Щелкните правой кнопкой мыши на модульном тестовом приложении WP8 и выберите «Управление пакетами Nuget»; Теперь выполните поиск wptoolkit, как показано ниже.

образ

Вы хотите установить инструментарий Windows Phone и Windows Phone Toolkit Test Framework. После этого у вас будут необходимые файлы для модульного тестирования ваших проектов WP8. Немногое изменилось, за исключением нескольких новых ссылок и изображений, которые были добавлены для вас.

Перейдите к файлу MainPage.xaml.cs и добавьте следующее:

// Constructor
public MainPage()
{
    InitializeComponent();
    this.Content = UnitTestSystem.CreateTestPage();           
}   

Вам нужно будет исправить использование вами заявлений, так как это использует: Microsoft.Phone.Testing.

Если вы установите этот проект в качестве начального проекта и развернете его в эмуляторе, вы получите следующий экран:

1

Если мы нажмем кнопку воспроизведения, то обнаружим, что у нас нет тестов для запуска.

2

Let’s go ahead and add a reference to our real WP8 application by right clicking references and browsing to solution then projects as shown below.

образ

Now that we have a reference to our main project, let’s go ahead and add a simple method that we will use with our Unit Test application.

Navigate to your MainPage.xaml.cs in your main project and add the following code snippet under the MainPage constructor.

public static int AddIntegers(int a, int b)
{
    return (a + b);
}

That was real hard wasn’t it? OK, this will simply add two numbers and return the value. (I hope you had that part figured out.)

Let’s return to our Unit Test project and creating a new folder called, “UnitTests” and add a class called “WP8UnitTest”.

Drop in the following code snippet (you may have to change your namespace if you didn’t name this project UnitTestWP8App)

using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Linq;

namespace UnitTestWP8App.UnitTests
{
    [TestClass]
    public class WP8UnitTest
    {
        [TestMethod]
        [Description("Check to see if MainPage.xaml get instantiated")]
        public void MainPageTest()
        {
            //Should return true
            MyAwesomeWP8App.MainPage MPage=new MyAwesomeWP8App.MainPage();
            Assert.IsNotNull(MPage);
        }

        [TestMethod]
        [Description("Check to see if AddIntegers works as desired")]
        public void AddIntegersTestShouldPass()
        {
            //Should Pass Since we are using Assert.IsTrue and 2+3=5
            var c=MyAwesomeWP8App.MainPage.AddIntegers(2, 3);
            Assert.IsTrue(c == 5);
        }

        [TestMethod]
        [Description("Check to see if AddIntegers works as desired")]
        public void AddIntegersTestShouldPass2()
        {
            //Should Pass since we are using Assert.IsFalse and 2+3 does not equal 7
            var c=MyAwesomeWP8App.MainPage.AddIntegers(2, 3);
            Assert.IsFalse(c == 7);
        }
    }
}

From here, we have 3 TestMethods that are going to run.

  • The First one just checks to see if the MainPage.xaml gets instantiated in our main application.
  • The Second one calls our AddIntegers method and adds two numbers and expect the result to be 5.
  • The Third one calls our AddIntegers method and adds two numbers and expects the result to NOT equal 7.

If we run our Unit Test Application now and hit the play button, then we can see all three tests passed.

3

We can also drill into them and get more details as well as email it or save it to isolated storage.

4

Wrap-up

I hope this helps you understand Unit Testing in WP8. As always, I’m available for any type of help that you may need. You may also download the completed project here.