Pascal
Pascal

Reputation: 12855

Unit testing with identity columns

I am using IDENTITY columns in my SQL Server tables.

I have a unit test where I delete a data record with a certain id.

When I insert the testdata I get this exception:

Cannot insert explicit value for identity column in table 'MyTablename' when IDENTITY_INSERT is set to OFF

Then I do a quick test in my management studio:

SET IDENTITY_INSERT MyTablename ON

It says Command(s) completed successfully.

I rerun the unit test but still get the same error.

How do I go about that in general? I want that my unit testing database with all tables should allow me to insert a value manually for an identity column.

Upvotes: 1

Views: 1334

Answers (1)

anon
anon

Reputation:

SET IDENTITY_INSERT is session-specific. You can't set it to true in SSMS and then go run a unit test in some other rig. The SET command needs to be part of the unit test code.

Also, you can only set this setting to one table at a time, so it doesn't seem like your unit test will work very well unless you set each table as you need it.

Upvotes: 3

Related Questions