views:

120

answers:

2

Hi, This is a sample function that works with an entity, saves it to a db and then causes problems because we can't write a Unit Test for it. Check it out:

// this class exists in a Silverlight Class Library
public class EmployeeSaver
{
    ....

    public void Go()
    {
        Employee e = new Employee();

        e.Name="Jeremiah";

        ... // Other stuff that really needs to be tested

        _DataContext.Employees.Add(e);
        _DataContext.SubmitChanges();

    }
}

Because the nature of RIA Services, a DomainService doesn't run inside of the Silverlight Unit Testing framework. This means I don't have access to RIA when I do my unit tests.

We've thought about mock databases, but this class actually creates an Entity (Employee) to be added to the DB. This is problematic because Mock Databases don't use this entity but a MockEntity class that looks similar to the original entity.

We're not trying to test RIA itself, but how we use the entities generated by RIA.

My end goal would be to write a function similar to this:

[TestMethod]
public void Test()
{
    EmployeeSaver s = new EmployeeSaver();
    s.Go();

    Assert.IsEqual( DataContext.Employees.Last().Name, "Jeremiah" );
}

How can I test this function? What testing framework should I use? Am I way off for using the Silverlight Testing Framework?

+1  A: 

A hand rolled mock database could store your object as is. We use such a system where the repositories are stored in dictionaries of .

You don't even need to go that far though. You could just use a mock interface for the _DataContext with something like RhinoMocks to make sure that the methods you expect to be called were (its not your concern for this test that _DataContext.SubmitChanges() works (that would be up it it's unit test) you only care that Go set the object and called save.

ryber
+2  A: 

In your unit test, instance s needs to have a stubbed out implementation of _DataContext. When the Go method is called, and it calls: _DataContext.Employees.Add(e); _DataContext.SubmitChanges(); it will call into your stub. The stub should then record the fact that an employee got added and changes were submitted.

After the call to Go, you should query the stub to ensure that the new employee got added, and call to SubmitChanges occurred.

As a secondary note: I don't really agree with the last part of the other answer in that you should not care whether Go calls various methods of _DataContext. It is true that you're not concerned about testing _DataContext methods here, but the unit test for Go needs to ensure that the Go method is calling the _DataContext methods properly. The rationale is that every line of the Go method should be testable. If you didn't do this verification, then you could remove the calls to _DataContext method, breaking the code, but the unit test wouldn't catch it. This would break Bob Martin's the "three rules of TDD" principle.

zumalifeguard