Search code examples
c#.netado.nettddlinq-to-entities

.NET TDD with a Database and ADO.NET Entity Framework - Integration Tests


I'm using ADO.NET entity framework, and am using an AdventureWorks database attached to my local database server. For unit testing, what approaches have people taken to work with a database?

Obviously, the database has to be in a pre-defined state of change so that the tests can have some isolation from each other... so I need to be able to run through the inserts and updates, then rollback either between tests or after the batch of tests are done.

Any advice?

Thanks.


Solution

  • I have experienced a similar kind of situation.

    Storing data to DB and retaining them to previous state are not ideally unit tests. They are Integration test cases.

    In order to perform the integration tests (insert / update operations ) without affecting the actual data ,I would suggest the following

    1. Use different database(change the name of the actual DB) , and let the schema remain the same as the actual DB.

    2. Point the unit tests to the newly created DB.

    3. Now how do we create a new DB , for running the tests alone in an automated way ?

    Ans : Have the SQL scripts listed in a batch file , such as this.(here i presume you are using SQL SERVER)

    E.g., sqlcmd -i c:\data\runscripts\InventoryMonthEnd.sql

    Specify the batch file , which lodges this sql statement(s) to be executed in MSBuild process.

    Sample MSBuild Task .

    <ItemGroup>
    <StoredProcScripts Include="$(RelativeSPDir)/*.sql" />
    </ItemGroup>
    
    <Target>
    <Exec Command="isql -E -n -b -d DBName -i %(StoredProcScripts.Identity)" Condition="'%(StoredProcScripts.Identity)' != ''"/>
    </Target>