31 октября 2008

Unit Testing. Что это и чем это нам грозит?

Благодаря тлетворному влиянию прекрасного разработчика, моего коллеги, Никиты Говорова я начал изучать Best Practices. Первой из этих практик естественно стало модульное тестирование, к тому же в тот момент подоспел очередной preview ASP.NET MVC, а в месте с ним серия скринкастов MVC Storefront, с которыми я рекомендую ознакомиться, даже если вы не связаны с веб-разработкой.

Итак, модульное тестирование. Концепцию удобнее показать на примере.

Предположим, что перед нами стоит простая задача - написать целочисленный калькулятор. Как ни трудно догадаться основой его будет класс Calculator, который мы с вами и будем писать. Для удобства создадим интерфейс ICalculator, который покажет какие методы нам нужны:

public interface ICalculator
{
   int Add(int first, int second);
   int Substract(int first, int second);
   int Multiply(int first, int second);
   int Divide(int first, int second);
}

Далее нам нужно реализовать этот интерфейс в классе Calculator. Мы будем делать это поэтапно для каждого необходимого нам метода.

Этап 1: Написание теста

Да, как это парадоксально не звучит - сначала пишется тест, потом то, что тестируется. Это основное "неудобство" данной практики для новичков, так как очень сложно заставить писать тест еще до того, как написан сам код.

Для написания теста нам нужно добавить в наш Solution новый проект типа Test Project(в данной статье мы будем использовать встроенные тесты Visual Studio 2008).После его создания у нас появится класс UnitTest1 с атрибутом [TestClass], содержащий в себе метод TestMethod1 с атрибутом [TestMethod].

Для начала переименуем метод во что-нибудь более удобоваримое, например в Calculator_Add_MustAddFirstIntToSecondAndReturnTheResult(). Не пугайтесь такого длинного названия - вызывать напрямую этот метод вам нигде не придется, но это добавит ясность к тесту в том случае, когда их у вас в проекте станет несколько сотен. Основная идея - назвать метод так, чтобы по названию стало ясно, что он делает(тестирует).

Небольшая ремарка: Мой коллега Никита Говоров недавно предложил воспользоваться возможностью C# и писать название тестовых методов на русском языке. Это спорное с моей точки зрения решение, так как может вызвать труднонаходимые опечатки из-за переключения раскладки, но если у вас есть сложности с английским языком, то попробуйте - возможно это то, что вам нужно.

Теперь собственно напишем сам тест, который будет тестировать работу метода Add.

[TestMethod]
public void Calculator_Add_MustAddFirstIntToSecondAndReturnTheResult()
{
   Calculator calculator = new Calculator();

   int result = calculator.Add(1, 2);

   Assert.AreEqual(3, result);
}

Как видите - тут все просто. Мы создаем экземпляр класса Calculator, и вызываем у него метод Add, записывая результат. Последняя инструкция - собственно проверка равен ли первый аргумент(тот, результат, который мы ожидаем) второму(результат, который мы получили). Если это не так - метод Assert.AreEqual выбросит исключение. Тест считается пройденным(Passed), если не было выброшено ни одного исключения.

Этап 2: Провалим тест

На этом этапе мы должны убедится, что то что мы собираемся проверять - действительно это проверяет. Так как мы еще не реализовали сам метод Add запуск теста приведет к провалу(Failed), что нам и нужно. Запуск теста осуществляется кликом по телу метода и вызовом команды контекстного меню Run Tests.

Это может показаться излишним, но действительно довольно часто встречаются ситуации, когда тестовый проходит(Passed), хотя никаких условий этому не обеспечено. Например вы можете ошибиться и проверять вместо длины коллекции возвращенных объектов методом Assert.AreNotEqual(0, collection.Length) ее неравность null методом Assert.IsNotNull(collection). При количестве элементов равном нулю ваш тест пройдет, хотя должен быть Failed.

Этап 3: Реализуем метод

На этом этапе с одной стороны все просто, с другой - не очень. Необходимо написать минимальный функционал, благодаря которому тест пройдет. Для примера возьмем метод Divide. Мы уже написали для него тест на предыдущем этапе:

[TestMethod]
public void Calculator_Divide_MustDivideFirstIntBySecondAndReturnTheResult()
{
   Calculator calculator = new Calculator();

   int result = calculator.Divide(4, 2);

   Assert.AreEqual(2, result);
}

В момент реализации самого метода вы можете подумать: "Черт, а ведь на ноль делить нельзя - надо добавить проверку". И будете не правы, так как ваш тест не учитывает этого функционала. Для написания такого функционала нужно написать еще один тест:

[TestMethod]
public void Calculator_Divide_MustCheckSecondArgumentOnZeroAndThrowExceptionIfTrue()
{
   Calculator calculator = new Calculator();

   bool catched = false;

   try
   {
       int result = calculator.Divide(4, 0);
   }
   catch (Exception ex)
   {
       Assert.IsInstanceOfType(ex, typeof (ArgumentException));
       catched = true;
   }
   Assert.IsTrue(catched, "No exception throwed - something wrong");
}

И только после этого реализовывайте соответствующий функционал.

Этап 4: Проходим тест

Последний этап самый простой - убедится что тест прошел.

Заключение

Как видите использование данной практики связано с большим расходом времени(нормальное соотношение строк кода к тестам - 1:2) и очень большой силой самоконтроля - непросто заставить себя идти ровно по шагам не забегая вперед тестов. Но - это того стоит. Во время написания тестов находится много потенциальных логических ошибок, которые в противном случае всплыли бы на этапе выполнения.

В этой статье мы использовали Unit Test Framework, который идет в комплекте с Visual Studio. В следующей статье мы рассмотрим альтернативный - MbUnit.

До новых встреч.

14 комментариев:

Анонимный комментирует...

[color=#5588aa]Анализ кредитного портфеля. Источника права. Право акционера на преобладающее приобретение дополнительно выпущенных акций. Полезная модель. [/color]
[url=http://tapikort.ru/]соционика[/url]

Анонимный комментирует...

Hi !.
You may , perhaps very interested to know how one can make real money .
There is no need to invest much at first. You may start earning with as small sum of money as 20-100 dollars.

AimTrust is what you haven`t ever dreamt of such a chance to become rich
The firm represents an offshore structure with advanced asset management technologies in production and delivery of pipes for oil and gas.

Its head office is in Panama with structures around the world.
Do you want to become really rich in short time?
That`s your chance That`s what you wish in the long run!

I`m happy and lucky, I began to get real money with the help of this company,
and I invite you to do the same. It`s all about how to select a proper partner utilizes your funds in a right way - that`s the AimTrust!.
I take now up to 2G every day, and what I started with was a funny sum of 500 bucks!
It`s easy to start , just click this link http://nosoxikah.arcadepages.com/jiqirax.html
and go! Let`s take our chance together to become rich

Анонимный комментирует...

Good day !.
You may , probably very interested to know how one can manage to receive high yields .
There is no initial capital needed You may start to receive yields with as small sum of money as 20-100 dollars.

AimTrust is what you haven`t ever dreamt of such a chance to become rich
The company represents an offshore structure with advanced asset management technologies in production and delivery of pipes for oil and gas.

Its head office is in Panama with structures everywhere: In USA, Canada, Cyprus.
Do you want to become really rich in short time?
That`s your choice That`s what you wish in the long run!

I`m happy and lucky, I began to take up income with the help of this company,
and I invite you to do the same. It`s all about how to select a proper companion utilizes your money in a right way - that`s it!.
I make 2G daily, and my first deposit was 1 grand only!
It`s easy to get involved , just click this link http://buqutevyd.mindnmagick.com/luvafu.html
and go! Let`s take our chance together to feel the smell of real money

Анонимный комментирует...

Hi !.
You may , probably curious to know how one can reach 2000 per day of income .
There is no initial capital needed You may commense to receive yields with as small sum of money as 20-100 dollars.

AimTrust is what you need
AimTrust incorporates an offshore structure with advanced asset management technologies in production and delivery of pipes for oil and gas.

Its head office is in Panama with affiliates around the world.
Do you want to become really rich in short time?
That`s your chance That`s what you desire!

I`m happy and lucky, I began to take up real money with the help of this company,
and I invite you to do the same. If it gets down to choose a proper partner utilizes your savings in a right way - that`s it!.
I take now up to 2G every day, and what I started with was a funny sum of 500 bucks!
It`s easy to get involved , just click this link http://nyceraso.lookseekpages.com/gonyduwe.html
and lucky you`re! Let`s take our chance together to get rid of nastiness of the life

Анонимный комментирует...

Hello !.
You re, I guess , probably curious to know how one can collect a huge starting capital .
There is no need to invest much at first. You may begin to get income with as small sum of money as 20-100 dollars.

AimTrust is what you thought of all the time
AimTrust incorporates an offshore structure with advanced asset management technologies in production and delivery of pipes for oil and gas.

It is based in Panama with structures around the world.
Do you want to become a happy investor?
That`s your chance That`s what you desire!

I`m happy and lucky, I started to get income with the help of this company,
and I invite you to do the same. It`s all about how to choose a proper partner who uses your savings in a right way - that`s it!.
I take now up to 2G every day, and my first investment was 500 dollars only!
It`s easy to get involved , just click this link http://kaxumumoh.100megsfree5.com/hujasaw.html
and go! Let`s take our chance together to feel the smell of real money

Анонимный комментирует...

Good day !.
You may , probably very interested to know how one can reach 2000 per day of income .
There is no need to invest much at first. You may commense to receive yields with as small sum of money as 20-100 dollars.

AimTrust is what you need
The firm incorporates an offshore structure with advanced asset management technologies in production and delivery of pipes for oil and gas.

It is based in Panama with affiliates around the world.
Do you want to become really rich in short time?
That`s your chance That`s what you wish in the long run!

I`m happy and lucky, I started to take up income with the help of this company,
and I invite you to do the same. If it gets down to choose a proper companion who uses your savings in a right way - that`s it!.
I earn US$2,000 per day, and what I started with was a funny sum of 500 bucks!
It`s easy to start , just click this link http://ruqobokux.1accesshost.com/sojuku.html
and go! Let`s take this option together to feel the smell of real money

Анонимный комментирует...

[color=#5588aa]Музыкальный ансамбль [url=http://dejavu-group.ru/about_us.php]Deja Vu[/url] - это коллектив заслуженных вокалистов и музыкантов.
[url=http://dejavu-group.ru/artist.php]Dejavu-group[/url]- законодатель в области организации и проведения дней рождения.
В копилке Музыкантов Deja Vu более 3тыс. песен.
Только живое исполнение. Ретро, хиты 70-80-90-х, джаз, диско, поп, современная музыка, европейские хиты, фоновая музыка, шансон.
Группа Deja Vu располагает мощной качественной музыкальной аппаратурой, позволяющей наполнить приятным уху звуком как небольшое помещение (фуршет), так и огромное помещение (корпоратив до 1 тыс. человек).

Андрей +7 910 483 8294 [/color]

Анонимный комментирует...

порядок разработки разработка сайтов http://web-miheeff.ru порядок разработки

Анонимный комментирует...

Good day, sun shines!
There have been times of troubles when I felt unhappy missing knowledge about opportunities of getting high yields on investments. I was a dump and downright pessimistic person.
I have never thought that there weren't any need in large initial investment.
Now, I feel good, I begin to get real money.
It gets down to choose a correct companion who uses your funds in a right way - that is incorporate it in real business, and shares the profit with me.

You may get interested, if there are such firms? I'm obliged to tell the truth, YES, there are. Please get to know about one of them:
[url=http://theblogmoney.com] Online investment blog[/url]

Анонимный комментирует...

Good day, sun shines!
There have were times of troubles when I felt unhappy missing knowledge about opportunities of getting high yields on investments. I was a dump and downright stupid person.
I have never imagined that there weren't any need in big initial investment.
Now, I'm happy and lucky , I started to get real income.
It's all about how to select a proper partner who uses your money in a right way - that is incorporate it in real business, parts and divides the income with me.

You may get interested, if there are such firms? I have to answer the truth, YES, there are. Please be informed of one of them:
http://theblogmoney.com

Анонимный комментирует...

[color=#5588aa]Музыканты на праздник [url=http://dejavu-group.ru/svadba.php]Dejavu-group[/url] - это коллектив профессиональных вокалистов и музыкантов на праздник.
[url=http://dejavu-group.ru/index.php]Dejavu-group[/url]- лидер в области организации и проведения музыкальных мероприятий, свадеб, юбилеев.
В репертуаре музыкальной группы Dejavu-group около 3000 песен.
Только живое исполнение. Ждаз, ретро, хиты 70-80-90-х, диско, поп, шансон, фоновое сопровождение .
Музыканты на праздник Dejavu-group обладает мощной качественной музыкальной аппаратурой, позволяющей наполнить приятным уху звуком как небольшое помещение (фуршет), так и огромное помещение (корпоратив до 1 тыс. человек).

Игорь +7 916 623 4047, Андрей +7 910 483 8294 [/color]

Анонимный комментирует...

проститутки минск транс
иркутские проститутки


http://ayongete.100webspace.net/nayti-devushek-dlya-seksa-v-astrahani-prostitutku.html проститутки киева цены
http://ayongete.100webspace.net/foto-prostitutki-odessy-2000-god.html какак стать проституткой



[url=http://ayongete.100webspace.net/samye-deshovye-prostitutki-pitera.html] досуг саратов проститутки зарегистрирован [/url]
[url=http://ayongete.100webspace.net/prostitutki-v-gorod-e-volhov.html] проститутки-индивидуалки в туле [/url]

Анонимный комментирует...

Glad to materialize here. Good day or night everybody!

We are not acquainted yet? It’s easy to fix,
my name is James F. Collins.
Generally I’m a social gmabler. recently I take a great interest in online-casino and poker.
Not long time ago I started my own blog, where I describe my virtual adventures.
Probably, it will be interesting for you to find out my particular opinion on famous gambling projects.
Please visit my diary. http://allbestcasino.com I’ll be glad would you find time to leave your comments.

Анонимный комментирует...

Glad to greet you, ladies and gentlemen!

For sure you didn’t here about me yet,
my parents call me Peter.
Generally I’m a venturesome analyst. recently I take a great interest in online-casino and poker.
Not long time ago I started my own blog, where I describe my virtual adventures.
Probably, it will be interesting for you to read my notes.
Please visit my blog. http://allbestcasino.com I’ll be glad would you find time to leave your comments.