SSDT Negative Database Unit Test

In one of my previous post I’ve faced with exception that occurred during unit test. Placing an appropriate command to disable constraints helps to avoid exception. But what should we do if we want to check that T-SQL code really fires an exception? The answer is very simple – we need to write a test that will handle the exception. This technique is called “negative testing”.

I will use the same example that I described in my previous test.

  • I change the Pre-test section to enforce constraints. Just place this command:
ALTER TABLE Clients CHECK CONSTRAINT ALL;
  • open the C# code of unit test: right-click the test in Solution Explorer, then click View Code
view csharp code of unit test
  • find the definition of our test (search for string dbo_CreateClientTest)
  • change the line in square brackets above the definition by adding a ExpectedSqlException attribute
attributes of test method

Message number and severity code was taken from the output of failed test that was run before. All possible properties that can be used in ExpectedSqlException declaration are explained here.
Note: The test will work even if you omit all the properties but using the exact values gives you the better level of granularity to check the right kind of exceptions.

 Now we can run our test. This time we see a green mark – our test passes.
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s