lundi 26 janvier 2015

Unit test architecture vs Activerecord architecture (.NET / C#)

First of all, I'm a little bit new in unittesting development, so please correct me if I go about it all wrong.


I'm a little bit of a fan of Activerecord, If the preformance would not be harmed I would have liked to save any change of any property of my record instantly. So:



var member = MyMembers.Get("John");
member.Name = "Elton John";


Would mean John has just become a famous singer in the database.


BUT:


Here comes unit testing, where this behaviour is not correct, to say the least. Any direct connection with the database must be taken away and should be "testeble", meaning you have to be able to write a test case with a virtual datacontext of records.


Now given the example my code would probebly look something like this:


(Note: I would normally add a Save() function, because it has better preformance with multiple property changes.)



public class MyMembers
{
public static MyMember Get(string Name)
{
MembersDataContext dc = new MembersDataContext();
var record = dc.Members.FirstOrDefault(a => a.Name == Name);
if (record == null) return null;
else return new MyMember(dc, record);
}
}

public class MyMember
{
public MyMember(MembersDataContext _dc, Member _record)
{
dc = _dc;
record = _record;
if (dc == null) throw new Exception("MyMember.MyMember: dc == null");
if (record == null) throw new Exception("MyMember.MyMember: record == null");
}

private MembersDataContext dc { get; set; }
private Member record { get; set; }

public int MemberID
{
get
{
return record.MemberID;
}
}

public string Name
{
get
{
return record.Name;
}
set
{
record.Name = value;
dc.SubmitChanges();
}
}

private List<MyProduct> _Products { get; set; }
public List<MyProduct> Products
{
get
{
if (_Products == null) _Products = MyProducts.Get(this);
return _Products;
}
}
}

public class MyProducts
{
public static List<MyProduct> Get(MyMember ForMember)
{
ProductProxy proxy = new ProductProxy();
return ProductProxy.GetProductsForMemberID(ForMember.MemberID).Select(a => new MyProduct(proxy, a));
}
}

public class MyProduct
{
public MyProduct(ProductProxy _dc, ProductProxy.Product record)
{
dc = _dc;
record = _record;
if (dc == null) throw new Exception("MyProduct.MyProduct: dc == null");
if (record == null) throw new Exception("MyProduct.MyProduct: record == null");
}

private ProductProxy dc { get; set; }
private ProductProxy.Product record { get; set; }

public int ProductID
{
get
{
return record.ProductID;
}
}

public string Name
{
get
{
return record.Name;
}
}
}


What I'm curious about is how I could "upgrade" this to suit better unit testing envirements.


Could you guys help me out?


Willem


Aucun commentaire:

Enregistrer un commentaire