What is the purpose of unit testing an interface repository

Posted by ahsteele on Stack Overflow See other posts from Stack Overflow or by ahsteele
Published on 2010-06-17T23:09:15Z Indexed on 2010/06/17 23:13 UTC
Read the original article Hit count: 242

Filed under:
|
|
|

I am unit testing an ICustomerRepository interface used for retrieving objects of type Customer.

  • As a unit test what value am I gaining by testing the ICustomerRepository in this manner?
  • Under what conditions would the below test fail?
  • For tests of this nature is it advisable to do tests that I know should fail? i.e. look for id 4 when I know I've only placed 5 in the repository

I am probably missing something obvious but it seems the integration tests of the class that implements ICustomerRepository will be of more value.

[TestClass]
public class CustomerTests : TestClassBase
{
    private Customer SetUpCustomerForRepository()
    {
        return new Customer()
        {
            CustId = 5,
            DifId = "55",
            CustLookupName = "The Dude",
            LoginList = new[]
            {
                new Login { LoginCustId = 5, LoginName = "tdude" },
                new Login { LoginCustId = 5, LoginName = "tdude2" }
            }
        };
    }

    [TestMethod]
    public void CanGetCustomerById()
    {
        // arrange
        var customer = SetUpCustomerForRepository();
        var repository = Stub<ICustomerRepository>();

        // act
        repository.Stub(rep => rep.GetById(5)).Return(customer);

        // assert
        Assert.AreEqual(customer, repository.GetById(5));
    }
}

Test Base Class

public class TestClassBase
{
    protected T Stub<T>() where T : class
    {
        return MockRepository.GenerateStub<T>();
    }
}

ICustomerRepository and IRepository

public interface ICustomerRepository : IRepository<Customer>
{
    IList<Customer> FindCustomers(string q);
    Customer GetCustomerByDifID(string difId);
    Customer GetCustomerByLogin(string loginName);
}

public interface IRepository<T>
{
    void Save(T entity);
    void Save(List<T> entity);
    bool Save(T entity, out string message);
    void Delete(T entity);
    T GetById(int id);
    ICollection<T> FindAll();
}

© Stack Overflow or respective owner

Related posts about c#

Related posts about unit-testing