‘Expected to find an element’ error when running VS2010 Database unit tests

If you use the database unit testing feature of VS2010 there is a good chance you will want to run these tests on more than one PC and probably the build server. The issue is that these different PC will need different deployment paths and SQL connection strings. Luckily there is a feature to address this, as detailed on MSDN. Basically the test runner swaps in a different config file based on either the PC name or user running the tests.

This all seems straight forward, but when I followed the process and ran my tests they failed

image 

The most useful error is found if you get the test run details (the button highlighted in green). You can see that it found the file replacement config file but failed to parse it giving the error

An error occurred while reading file C:\…\TestResults\fred_PCNAME 2011-09-12 22_33_11\Out\buildbox.dbunittest.config : Expected to find an element.

[It is work noting here it is easy to forget to make sure the buildbox.dbunittest.config is deployed to the test folder as detailed on MSDN. If you forget this you get a file not found error not an ‘expected to find an element’ error]

So I checked my buildbox.dbunittest.config file to look for typos. The MSDN instructions say to copy the app.config and make your edits, but then goes onto mention after editing it should resemble.

<DatabaseUnitTesting> 
       <DatabaseDeployment DatabaseProjectFileName="..\..\..\Sources\UnitTest\UnitTest\UnitTest.dbproj" Configuration="Debug" />
       <DataGeneration ClearDatabase="true" />
       <ExecutionContext Provider="System.Data.SqlClient" ConnectionString="Data Source=.\SQLEXPRESS;
                       Initial Catalog=UnitTestB;Integrated Security=True;Pooling=False" CommandTimeout="30" />
       <PrivilegedContext Provider="System.Data.SqlClient" ConnectionString="Data Source=.\SQLEXPRESS;
                       Initial Catalog=UnitTestB;Integrated Security=True;Pooling=False" CommandTimeout="30" />
</DatabaseUnitTesting> 

It should NOT include the <?xml version="1.0" encoding="utf-8" ?>, <configuration> or <configSections> tags. This as been stressed in some forum posts. However even when I made sure my buildbox.dbunittest.config first line was <DatabaseUnitTesting> I still got the same error.

Turns out the issue was that I had leading white space before the <DatabaseUnitTesting>, once this was done the test ran as expected.