Create multiple criteria to mock DataAcess in CSLABO

I posted before about using TypeMock to do mock data access in CSLABO. Today I am posting another way to mock dataaccess without using TypeMock.

First, I need to create IRepository<DTO> interface:

public interface IRepository<DTO>
DTO FindById(int id);
DTO Insert(DTO data);
void Update(DTO newData, DTO oldData);
void Delete(DTO data);
void DeleteById(int id);

Second, create my OrganizationRepository by implementing this IRepository<OrgarnizationDTO>.

Third, in my BO, add those 2 fetch methods:

private void DataPortal_Fetch(SingleCriteria<OrganizationBO, int> criteria)
DataPortal_Fetch(new RepositoryCriteria<OrganizationDTO>(new OrganizationRepository(), criteria));

private void DataPortal_Fetch(RepositoryCriteria<OrganizationDTO> repositoryCriteria)
var data = repositoryCriteria.Repository.FindById(
((SingleCriteria<OrganizationBO, int>)repositoryCriteria.Criteria).Value );

if (data != OrganizationDTO.NULL)

public class RepositoryCriteria<DTO>
public IRepository<DTO> Repository;
public CriteriaBase Criteria;

public RepositoryCriteria(IRepository<DTO> repository, CriteriaBase criteria)
Criteria = criteria;
Repository = repository;

Finally, The test code:

public void CanFetchFromMoQRepository()
var mockRepository = new Moq.Mock<IRepository<OrganizationDTO>>();

// Id in MoQ matters. TypeMock doesn’t.
mockRepository.Expect(x => x.FindById(8172)).Returns(
new OrganizationDTO
Id = 1,
Name = “A test org name”

var o = DataPortal.Fetch<OrganizationBO>(
new RepositoryCriteria<OrganizationDTO>(
new SingleCriteria<OrganizationBO, int>(8172)

Assert.AreEqual(1, o.Id);
Assert.AreEqual(“A test org name”, o.Name);

The benefit of this solution is we are a little bit close to loose coupling, but later I figured out it’s still very hard to mock the Save() method. Had to back to TypeMock.


Leave a Reply

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

You are commenting using your 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