Creating a basic MVC 6 web application with Entity Framework 7 and xUnit - Part 1

In my first post I'm showing you how to set up a basic MVC 6 web application with Entity Framework 7. Before we do any controllers, or creating any databases, we use xUnit and moq for creating a mock database context and testing our service. You can clone the repository with this sample from Github.

1. Creating the projects

Open Visual Studio 2015 RC and select New project.

Make sure you choose .NET Framework 4.6. Now create an empty ASP.NET 5 project.

Now create two projects of type Class Library, Sample1Data and Sample1DataTests:

You should now have 3 projects in your solution:

Next we need to install MVC 6, Entity Framework 7 and xUnit. To do this, we don't use the NuGet UI. It's easier to edit the project.json file of each project and adding the references there. Enjoy the Intellisense ;). Begin with the Sample1 project. Make sure you dependencies section looks like this:

As you can see, we already added a dependency to our Sample1Data project. Next up is the Sample1Data project:

And finally the Sample1DataTests project. Don't forget the commands part needed for the test runner.

Here we need to comment out the dnxcore50 framework since it's currently not supported by moq. This isn't a problem here since it's just the test project.

Now save and rebuild the solution. NuGet should automatically download all packages.

2. Defining a model and creating a simple test

In our Sample1Data project we need to add 2 classes: The model and a service class. Additionally, we add an interface for our data context.

Now that we have our data classes ready, we can write our first unit test in Sample1DataTests:

We aren't using MVC yet, but you can already add an implementation for the IDataContext in the web project:

Now we need to add this data context in Startup.cs

Rebuild the solution and open up the test explorer (in the VS menu, choose Test, Windows, Test Explorer). Now click Run all and our first test should be found, run and pass.

In the next parts we're connecting to a database, add controllers, add client-side code using TypeScript and add unit tests for testing this client-side code.

Comments

Popular posts from this blog

Debugging Lua scripts in VS Code using MoonSharp

Testing the response body of middleware in ASP.NET Core

Creating a basic MVC 6 web application with Entity Framework 7 and xUnit - Part 2