Question

I have a 4 tier application

1) Presentation (MVC)
2) Service (WCF)
3) Business
4) Data

Some methods in my service layers perform a lot of other sub processes for e.g.,

public OrderResponse PlaceOrder(OrderRequest request)
{
     if (CheckForSufficientStock(request.ItemId)) {
          ReserveStock(request.ItemId);
          ProcessPayment(request.CustomerPaymentDetails);
          RemoveStockFromInventory(request.ItemId);
          ArrangeForShipping(request.CustomerDetails);
          AddToOrderHistory(request);          
     }
}

I'm starting to learn how to write unit tests, and I have a few questions

1) Which layer should I write unit tests for? Do I write my unit tests for my controllers in the MVC project? Or do I have to write unit tests for each method in my service layer? Or both?

2) If I have to write unit tests for both MVC & Service layer, am I right to say, the unit tests in my MVC project will test PlaceOrder, and the unit tests to test my service layer will test all the sub functions e.g., ReserveStock, ProcessPayment, etc?

Was it helpful?

Solution

Generally you need end to end tests as well as unit tests. I don't want to explain the basic concept but I just want to list some best practice from my own experience.

For doing the unit tests, only test one layer at a time by mocking the layer it based on. For example, when you test Business layer, you should mock the Data access layer. By mocking the layer below, you can logically isolate the code stub you want to test without touching other layers. This approach not only is easy to work with, but also you can prevent testing too much things and get false alarms. You can also prepare test fixture to make sure every time you run test, you actually do the dry run.

Here are some popular technology you can use to do the unit testing:

  • To test Javascipt in the View Layer you can use Jasmine etc
  • To test the C# code, you can use MSTest, nUnit, xUnit
  • To mock the C# layer, you can use Moq
  • To do the end to end testing, you can use Selenium

OTHER TIPS

We all know, Unit Testing means testing single scenario at a time. You would have to write unit tests for all the layers. For Example, in you case, In MVC PlaceOrder method, your test cases can be: whether CheckForSufficientStock input parameter in not null, or Verify each function is called TimesOnce. Similarly, in other layers, Say

CheckForSufficientStock(int something)
{
...
}

Same thing will be followed, if any function is called again, then verify Times, return values. Mocking is required to skip actual calls to other layers or functions, by faking it with return values, which is the required thing to proceed to next line of code. I have found Moq is best for beginners to use.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top