Unit Testing & Primary Keys

unit testing

I am new to Unit Testing and think I might have dug myself into a corner.

In your Unit Tests, what is the better way to handle primary keys?

Hopefully an example will paint some context. If create several instances of an object (Lets' say Person).

My unit test is to test the correct relationships are being created.

My code is to create Homer, he children Bart and Lisa. He also has a friend Barney, Karl & Lenny.

I've seperated my data layer with an Interface. My preference is to keep the primary key simple. Eg On Save, Person.ProductID = new Random().Next(10000); instead of say Barney.PersonID = 9110 Homer.PersonID = 3243 etc.

It doesn't matter what the primary key is, it just needs to be unique.

Any thoughts???

EDIT:

Sorry I haven't made it clear. My project is setup to use Dependency Injection. The data layer is totally separate. The focus of my question is, what is practical?

Best Answer

I have a class called "Unique" which produces unique objects (strings, integers, etc). It makes sure they're unique per-test by keeping a internal static counter. That counter value is incremented per key generated, and included in the key somehow.

So when I'm setting up my test

var Foo = {
    ID = Unique.Integer()
}

I like this as it communicates that the value is not important for this test, just the uniqueness.

I have a similar class 'Some' that does not guarantee uniqueness. I use it when I need an arbitrary value for a test. Its useful for enums and entity objects.

None of these are threadsafe or anything like that, its strictly test code.

Related Topic