This project has moved and is read-only. For the latest updates, please go here.

This tutorial shows a very basic approach of unit testing. We are going to test this simple data component:

public class ProductService : IProductService
{
    public NorthwindEntities Context { set; get; }

    public Product GetProduct(int id)
    {
        return Context.Products.FirstOrDefault(p => p.ProductID == id);
    }

    public void DeleteProduct(Product product)
    {
        Context.Products.Attach(product);

        Context.Products.DeleteObject(product);
        Context.SaveChanges();
    }
}

The component provides two simple operations: querying and deleting the Product entities from the database. If an entity is deleted, it obviously cannot be queried anymore. The next unit test verifies this behavior.

In the initializer method creates the fake object context for each unit test.

private NorthwindEntities context;

[TestInitialize]
public void Initialize()
{
    IDataLoader loader =
        new Effort.DataLoaders.CsvDataLoader(Settings.TestDataPath);
    this.context =  
        Effort.ObjectContextFactory.CreateTransient<NorthwindEntities>(loader);
}
 

Now we can write our test methods. The first test method verifies if an enity exist with a specific ID.

[TestMethod]
public void ProductExist()
{
    // Arrange
    ProductService service = new ProductService { Context = context };

    // Act
    var result = service.GetProduct(1);

    // Assert
    Assert.IsNotNull(result);
}

The test is very simple, the data component is created and requested to query the Product entity whose ID equals 1. The test pass if the entity exists, so the result is not null. The second test method verifies if the data component can remove an entity from the database.

[TestMethod]
public void DeleteProduct()
{
    // Arrange
    ProductService service = new ProductService { Context = context };

    Product product = new Product();
    product.ProductID = 1;

    // Act
    service.DeleteProduct(product);

    // Assert
    product = service.GetProduct(1);

    Assert.IsNull(product);
}

The data component is initialized like in the previous test and requested to delete the Product entity whose ID equals 1. Then the component is requested to retrieve the same entity. The test pass if the entity does not exists, so the result is null.

If the initial data contains the requested record, the tests will pass regardless to the order of execution. This is possible, because every test starts consistently with the same initial data. The data manipulation done by a test does not effect the data context of another test.

Last edited Nov 10 at 6:18 AM by zzzprojects, version 15

Comments

No comments yet.