开发者

unit testing / integration guidance for a shopping cart

开发者 https://www.devze.com 2022-12-13 06:14 出处:网络
Need some guidance on how to go about unit testing a shopping cart (.net mvc, c#). I want to use sqllite as I am开发者_C百科 using nhibernate so I can create an in-memory version of my database for i

Need some guidance on how to go about unit testing a shopping cart (.net mvc, c#).

I want to use sqllite as I am开发者_C百科 using nhibernate so I can create an in-memory version of my database for integration testing.

So I have a Cart object:

public class Cart
{
      void Add(Item item);
      void Delete(Item item);

      void CalculateTotalBLah();
}

so the method Add might look like:

public void Add(Item item)
{
     ItemDAO item = new SomeFactory();

     item.Add(item);
}

So there are 2 things I have to test I guess:

  1. that the in-memory representation of the Cart object adds the item to the cart.
  2. the database is correctly in synch. with the in-memory object.

The database test I believe is fairly straight forward.

How do I test #1, how do I remove the dependancy of the db operations? Does nunit do this for me somehow?


You can use a repository pattern. Then create a Moq for the repository. The Mock should make sure the save was called. The shopping cart constructor should take an IRepository so you can either send in a Mock or the real thing.


It's very hard to unit test code using the active record pattern. You can make the code easier to test by using the "single responsibility principle", that means that one class is responsible for one thing. Your cart class is responsible for 2 things: data-access and the shopping cart business logic. You can make this code easier to test with a separate repository or a query object for the data-access. If you don't want to modify your code, you can try to mock things out with typemock isolator (other mocking frameworks cannot mock this kind of code as far as I know, but I never needed typemock personally)

0

精彩评论

暂无评论...
验证码 换一张
取 消