Почему бы не поражать базу данных в модульных тестах?

Мы выбрали № 2 при создании колеи. Я работал над API (ruby, sinatra и т. Д.), А мой деловой партнер, Стив Смит, работал над интерфейсом (клиент javascript).

Плюсы:

  1. Быстро двигаться параллельно. Если бы я работал раньше Стива, я мог бы продолжать создавать API для новых функций. Если бы он работал впереди меня, он мог бы очень легко подделать API и создать пользовательский интерфейс.

  2. API бесплатно. Наличие открытого доступа к данным в вашем приложении быстро становится стандартной функцией. Если вы начнете с API с нуля, вы получите это бесплатно.

  3. Чистое разделение. Лучше думать о вашем приложении как о API для клиентов. Конечно, первым и самым важным клиентом может быть веб-клиент, но он настраивает вас на простоту создания других клиентов (iPhone, Android).

Минусы:

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

Я не могу больше думать о минусах прямо сейчас.

Вывод: клиент API + JS - это то, что нужно, если вы планируете выпустить API.

P.S. Я также рекомендовал бы полностью документировать ваш API перед его выпуском. Процесс документирования API Gaug.es действительно помог нам чертить

http://get.gaug.es/documentation/api/

12
задан Hugo Zapata 28 June 2009 в 14:08
поделиться

7 ответов

You are simply in a semantic grey area.

  • System tests cover the whole system from end-to-end.
  • Unit tests can be used to describe a sub-segment of the end-to-end cycle.

In that case your unit tests of your application code would/might not hit the database, but you would/might have unit tests that covered your database stored procedures...

Basically divide your application into things to be tested along partitions that make sense. If you choose the wrong partition line you end up with a big code maintenance problem with mock objects and test scaffolding and stuff...

A common way with web apps is to write a series of unit tests that test the data access layer...

Then write a series of unit tests that test the application layer (including the data layer) ...

And finally write some browser-based system tests...

The trick is to only put information in and out of the middle set - the application layer - through the API and not burrow into the database to see if something worked. That way your tests won't break if you change the data schema.

But sometimes (as I actually currently doing as I write this) you HAVE to look into the database to make a meaningful and robust test suite (I am testing server-server transfer protocols).

Focus on the way that gets maximum code coverage and stability for your application, whilst writing the least amount of testing scaffolding, and avoiding brittleness in your test suite.

10
ответ дан 2 December 2019 в 19:32
поделиться

There are two main reasons for unit tests not hiting the database:

  • You want your tests to go as fast as possible
  • You want to test your code as a single unit, not how it integrates with other code/ database.

In your case you need to test the stored procedures. Then you need to write a test that runs those stored procedures. Either you can run them via your code (Integration test) or you can run them directly from the test (sort of a unit test). In both cases you can use Nunit.

4
ответ дан 2 December 2019 в 19:32
поделиться

YMHO There is a bit of semantic issue and a bit of a technical issue here.

A unit test is supposed to test a small part of code, in isolation, to check it without other code. A failed Unit Test should imply that only a small part of code will have to be inspected corrected (tipically, the code implementing the functionality and the unit test itself).

Other scopes of testing exist to check functionality of the system as a whole (system test), or functional tests to validate complete features, or integration tests to check interactions, regression testing to check for the absence of already corrected test etc.

A testing strategy has to be devised for each project, but in general having different categories helps a lot. So unit tests should be restricted to testing the smallest possible units of code, and use other testing procedure to test functionality, integration etc.

The semantic part is whether is correct to use a unit test library to perform some functional test, I guess it is no biggy if you keep your suites separated the strict unit tests and the functional tests (even if they share the testing tool)

1
ответ дан 2 December 2019 в 19:32
поделиться

Дело в том, что если ваши модульные тесты попадают в базу данных, вы не тестируете только одну единицу кода, а вместо этого выполняете несколько - также и DAL, хранящийся процедуры и т. д. Вот почему сторонники TDD советуют не попадать в базу данных в юнит-тестах.

Это также то, почему вы не должны иметь большого веса в чистых, концептуализированных TDD, теоретических святых U nit T ests. Хотя модульное тестирование само по себе не так уж и плохо, и на самом деле очень важно для обеспечения правильной сборки каждого компонента программистами, гораздо важнее системное тестирование. В целом, может быть труднее найти точный метод, который привел к сбою системных тестов, они более реалистичны и фактически тестируют систему .
So-called "Component Testing" - which is more like system testing, but for only one small part of the system, end-to-end - seems to me to be a good compromise.

(Cue the TDD rebuttals now... :) )

2
ответ дан 2 December 2019 в 19:32
поделиться

После написания Следует ли тестировать внутреннюю реализацию или тестировать только публичное поведение? и обсуждая ответы людей, я думаю, что ответ может зависеть от того, сколько человек входит в команду разработчиков.

Преимущества тестирования с базой данных:

  • Тестирование более реалистично (с использованием реальной базы данных)
  • Меньше тестирования код для записи (не нужно писать имитацию базы данных)

Недостатки тестирования с базой данных:

  • Ваши тесты не могут выполняться, пока не будет написан уровень доступа к базе данных
  • Если есть ошибка или провал теста, ты неНе знаю, в вашем коде или в уровне доступа к базе данных

. Недостатки особенно важны, если (но, возможно, только если) человек, пишущий верхний уровень, не совпадает с человеком, пишущим уровень доступа к базе данных.

1
ответ дан 2 December 2019 в 19:32
поделиться

The problem in adressing the database in your tests is that a change in the database or a change in your code can fail the test. A unit test normally should point as direct as possible to the change that made him fail. Поэтому, если вы хотите протестировать код для доступа к БД, возможно, используйте фиксированную тестовую базу данных. Таким образом, вы уверены, что код, который обращается к БД, неверен, потому что вы знаете, что база данных не изменилась, и если вы хотите изменить настройку БД, сначала измените тестовую БД и увидите, что ваш тест завершился неудачно, затем исправьте его, а затем измените не тестовая БД. В проекте, над которым я работал, мы создали небольшую базу данных, которая была сгенерирована в памяти перед каждым тестом.

0
ответ дан 2 December 2019 в 19:32
поделиться

"...the database should not be hit when the unit tests run..." - unless you're unit testing persistence objects, of course.

I don't know which blogs you're citing, but I'll bet what they're saying is that mocking some components during integration testing can have benefits. If you've already unit tested the persistence tier, there's no need to test it again. The benefit of mocking in that case has more to do with reducing dependencies and uncertainty. For example, you might have unit tested your code, packaged it up, and now it's time to move it into an environment that's closer to production. If the databases you need can't be available (e.g., don't have the proper version of the schema, missing data that you need, or simply needed by another application that got there first), you can use mocks to allow your integration test to proceed without delay.

0
ответ дан 2 December 2019 в 19:32
поделиться
Другие вопросы по тегам:

Похожие вопросы: