Skip to content

danushkap/unit-test-bl-with-webrequest

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

17 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

How to unit test a method (BL) that contains a web request ?

Azure DevOps builds Azure DevOps tests Azure DevOps coverage CodeFactor

GitHub license GitHub issues

Take a method (BL) that decide the membership type of a person based on the membership amount that he has paid. Where the method has to get the membership amount from a webservice.

MembershipType GetMembershipType()
{
    var membershipAmount => () 
    {
        // get the membership amount from a webservice
    }
    
    if (membershipAmount > 1000) return MembershipType.Platinum;
    else if (membershipAmount > 500) return MembershipType.Gold;
    else if (membershipAmount > 0) return MembershipType.Silver;
    else return MembershipType.NA;
}
PROBLEM

Now how to test the business logic that is in the GetMembershipType() without having to worry about the webservice that it depends?

SOLUTION

Apply the Dependency Inversion principle : decouple the webservice dependency from the BL method. And apply the Dependency Injection design pattern to inject that dependency from outside.

See how this is done:

https://github.com/danushkap/test-bl-with-webrequest/blob/master/BL/MembershipService.cs

See how this design has enabled to test the business rules without having to worry about the webservice call:

https://github.com/danushkap/test-bl-with-webrequest/blob/master/BL.Tests/MembershipService_GetMembershipTypeAsync.cs