A fact is immutable. You set its fields during construction. From that point on, it cannot be changed. Those fields identify the fact.

In this lesson, we will write unit tests to exercise a model.
  • Create a blank solution.
  • Add a Silverlight Class Library project called "Lesson.Model".
  • Add a NuGet reference. Search for Correspondence.Model
  • Move the contents of the Models folder into the root of the project.
  • Add a Silverlight Application project called "Lesson.UnitTest".
  • Add a NuGet reference. Search for Correspondence.Silverlight.UnitTest
  • Add a project reference to UnitTest. Select Model.
  • Add the namespace reference using Lesson.Model; to ModelTest.
  • The solution should now compile.

Open the model.fact file. Delete everything except for the following lines.
namespace Lesson.Model;

fact User {
key:
    string userName;
}


Click the "Transform All Templates" button in the Solution Explorer. This will regenerate the model from the Factual definition. Try to build the solution. It should compile.

You will find some commented lines in ModelTest that reference to the Identity fact type. Uncomment these lines and change Identity to User. Build the solution.

Modify the test to create a user. The user constructor takes a userName. You can later access this field through the UserName property. All facts need to be added to the community. Here's the completed test:
[TestMethod]
public void CreateAUser()
{
    User alan = _community.AddFact(new User("alan1"));
    Assert.AreEqual("alan1", alan.UserName);
}

The userName field is immutable. It can only be set during construction. The following code will not compile because the UserName property is read only.
[TestMethod]
public void UserNameIsImmutable()
{
    User alan = _community.AddFact(new User("alan1"));
    alan.UserName = "flynn1";
}

The fields determine the identity of the fact. If you pass different fields to the constructor, you will get back different instances.
[TestMethod]
public void UsersWithDifferentNamesAreDifferent()
{
    User alan = _community.AddFact(new User("alan1"));
    User flynn = _community.AddFact(new User("flynn1"));
    Assert.AreNotSame(alan, flynn);
}

But if you pass the same fields to the constructor, you will get back the same instance.
[TestMethod]
public void UsersWithSameNamesAreSame()
{
    User alan = _community.AddFact(new User("alan1"));
    User alanAgain = _community.AddFact(new User("alan1"));
    Assert.AreSame(alan, alanAgain);
}

That is why you must always pass a fact through the Community. It uses the provided fact as a prototype, but returns the exiting fact if it already has it.

Next: Lesson 1b: Unique

Last edited May 15, 2011 at 3:19 AM by MichaelLPerry1971, version 8

Comments

No comments yet.