bas
bas

Reputation: 14912

EntityFramework unit test example

I just solved my own question, but thought I'd might still be helpful for others to read so decided to post it anyway.


I am trying to get started with azure development and am currently at the stage of getting the database up and running. After a few hickups I achieved the following:

The last thing I'd like to see before I pick up the next challenge is to actually add something to my newly created database first. I'd thought the easiest way would be writing a test in nunit.

Here's what I got so far...

The entity class User:

namespace Models.Users
{
    public class User
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string EmailAddress { get; set; }
    }
}

The entity class UsersDb:

using System.Data.Entity;

namespace Models.Users
{
    public class UsersDb : DbContext
    {
         public DbSet<User> Users { get; set; }
    }
}

Generated the database with the following PS commands:

enable-migrations -ProjectName Models -ContextTypeName Models.Users.UsersDb
add-migration -ProjectName Models Initial
update-database -ProjectName Models 

Finally, I wrote the following unit test

using Models.Users;
using NUnit.Framework;

namespace Tests
{
    [TestFixture]
    public class DatabaseTests
    {
        [Test]
        public void AddUserTest()
        {
            var users = new UsersDb();
            var user = new User
                {
                    Id = 1, 
                    Name = "test", 
                    EmailAddress = "[email protected]"
                };

            users.Users.Add(user);
            users.SaveChanges();
        }
    }
}

That test runs, but throws an exception I can't figure out.

System.InvalidOperationException : The Entity Framework provider type 'System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' for the 'System.Data.SqlClient' ADO.NET provider could not be loaded. Make sure the provider assembly is available to the running application. See http://go.microsoft.com/fwlink/?LinkId=260882 for more information.

Solution

What I had to do to solve this, is open NuGet management (right click solution) and press the manage button on EntityFramework. In the dialog add a checkbox in front of your test solution, rebuild and go.

Now, I have a very small solution that creates a new user via a unit test and saves it into my database. A nice startup project which I can now start extending.

Upvotes: 4

Views: 1417

Answers (1)

bas
bas

Reputation: 14912

Solved the question while typing the question itself. Thought i'd still be useful as a reference for others.

Upvotes: 4

Related Questions