views:

193

answers:

3

I am Unit Testing with Subsonic 3.0.0.3. Unit tests ran as expected with record count assertions passing. However the testing framework does not auto increment identity columns.

For example

var p1 = new Person() { Name = "Jack" };
p1.Add();
var p2 = new Person() { Name = "Jill" };
p2..Add();
var t1 = Person.SingleOrDefault(p => p.Name == "Jack");
var t2 = Person.SingleOrDefault(p => p.Name == "Jill");

Table structure read by the T4 template

CREATE TABLE Person
(
    Id int IDENTITY(1,1) PRIMARY KEY
    ,Name NVARCHAR(255) NOT NULL 
)

Connection string

<add name="SomeDb" connectionString="Test"/>

t1 and t2 have the name property set as expected, but the Id property is 0 for both.

Is this by design? If so how to deal with tests that require selecting records by ID?

+2  A: 

The TestRepository has no idea how your DB bits are set (how could it?) so if you want it to auto-increment you'll need to set it yourself.

Rob Conery
+1  A: 

Here's a change to the ActiveRecord template that I find useful. Basically it handles an int or long primary key column and in test mode auto allocates a new id. Requires two changes to the ActiveRecord.tt template:

1: In the top of the function public void Add(IDataProvider provider){

        public void Add(IDataProvider provider){

<#if(tbl.PK.SysType=="long" || tbl.PK.SysType=="int") {#>
            if (TestMode)
            {
                this.<#=tbl.PK.CleanName#>=++next_test_autoid;
            }

<#}#>

2: Under the line public bool TestMode = false, add:

        public bool TestMode = false;
<#if(tbl.PK.SysType=="long" || tbl.PK.SysType=="int") {#>
        private static <#=tbl.PK.SysType#> next_test_autoid = 0;
<#}#>
cantabilesoftware
I didn't think of modifying the T4 templates directly. Thanks.
pauly
A: 

(I don't have enough points to comment yet, but this is in response to cantabilesoftware's answer.)

I have a subtype relationship in my database where two tables are 1->1. I had to modify your template slightly to skip the logic if the key field already has a value assigned:

<#if(tbl.PK.SysType=="long" || tbl.PK.SysType=="int") {#>
            if (TestMode && <#=tbl.PK.CleanName#> == 0)
            {
                this.<#=tbl.PK.CleanName#>=++next_test_autoid;
            }
<#}#>
G-Mac