Mock/Test DataAccess Funtions in CSLA

Note: This old post was to record our learning process of CSLA, we are currently using Repository + DTO Pattern in our CSLA project, and use StructureMap inject to implement mocking DataAccess.

CSLA doesn’t use Interface in DA, so mock DA is not possible? I thought so until I saw Nermin’s post about TypeMock.

Played it awhile. It works. The key point is, TypeMock is mocking against ‘Type’, instead of Interface which all the other mock tools against.

        Mock mockDb = MockManager.Mock(typeof (Database));

Notice Database is rewrote to encapsulate ADO object SqlCommand. The modified fetch function will like this:

private void DataPortal_Fetch(Criteria criteria)

    {

        /*   Old code:

              using (SqlConnection cn = new SqlConnection(Database.PTrackerConnection))

              {

                cn.Open();

                using (SqlCommand cm = cn.CreateCommand())

                {

                  cm.CommandType = CommandType.StoredProcedure;

                  cm.CommandText = "getProject";

                  cm.Parameters.AddWithValue("@id", criteria.Id);

                  using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader()))

        */

      using (Database db = new Database(Database.PTrackerConnection))

      {

        SqlCommand cm = db.CreateSPCommand("getProject");

        db.AddWithValue(cm, "@id", criteria.Id); /* This line Nermin pasted wrong in forum, so I fixed it. */

        using (SafeDataReader dr = db.ExecuteSafeDataReader(cm))

        {

The unit-test code:

using NUnit.Framework;

using TypeMock;

namespace ProjectTracker.Library.Test

{

    [TestFixture]

    public class ProjectTest

    {

        [SetUp]

        public void Start()

        {

            ///<remark>Initialize TypeMock before each test</remark>

            MockManager.Init();

        }

        [TearDown]

        public void Finish()

        {

            ///<remark>We will verify that the mocks have been called correctly at the end of each test</remark>

            MockManager.Verify();

        }

        [Test]

        public void TestWithTypeMock()

        {

            MockHelper.MockDatabaseFetchCall("PTrackerConnection", 1, new ProjectFetchOneDRStub());

            Project item = Project.GetProject(Guid.Empty);

            Assert.AreEqual("project name", item.Name);

        }

        [Test]

        public void TestWithNoMock()

        {

            Project item = Project.GetProject(new Guid("b2503d89-3845-4cee-86b4-375ff97b747e"));

            Assert.AreEqual("Expert C# Business Objects", item.Name);

            Assert.AreNotEqual("Expert C# Business Objects2", item.Name);

        }

    }

}
To make TeskWithNoMock pass, an App.config file needs to be created in Test project.
<?xml version="1.0" encoding="utf-8" ?>
<configuration>

	<appSettings>
		<!--  Csla , Windows-->
		<add key="CslaAuthentication" value="Csla" />
	</appSettings>
	<connectionStrings>
		<add name="PTracker"
				 connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename="C:\db\PTracker.mdf";Integrated Security=True;User Instance=False"
				 providerName="System.Data.SqlClient" />
		<add name="Security"
				 connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename="C:\db\Security.mdf";Integrated Security=True;User Instance=True"
				 providerName="System.Data.SqlClient" />
	</connectionStrings>

</configuration>

With BO test feature enabled, so far, I am very happy with CSLA. Need to figure out how deepData works. And how about the new LinQ in CSLA 3.5.

It’s my 2nd day of learning CSLA. To switch DA from WCF back to local mode by commenting  out the line in app.config

     <add key="CslaDataPortalProxy"
         value="Csla.DataPortalClient.WcfProxy, Csla"/>

“User Instance=False” in connectionStrings has to be changed from default true, otherwise DataPortal.Fetch failed (Cannot open user default database. Login failed.) Don’t know the reason yet, that’s the way it works.

The nice formated code above is generated by simple-talk.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s