Mock Unit Testing with Example

Mock Unit Testing with Example


Unit test cases should implement in our project, so as a developer we can assure that developed feature is working fine.

Here I have created a sample end to end.

DB Layer

//DB Layer: Database Class
public class tblUser
{
 public virtual string AddUser()
 {
  throw new NotImplementedException();
  //return "success";
 }
}
  

Business Layer

//Business Layer : Service Class
public class BLUser
{
 private readonly tblUser _BLUser;
 public BLUser(tblUser bLUser)
 {
  _BLUser = bLUser;
 }

 public string AddUser()
 {
  return _BLUser.AddUser();
 }
}
  

Implementation Layer

//Implementation Layer 
public class UserUI
{
 public string AddNew()
 {
  BLUser user = new BLUser(new tblUser());

  return user.AddUser();
 }
}
  

Test Project

//Unit Test: Test Class
[TestClass]
public class BLUserTest
{
 [TestMethod]
 public void AddUserTest()
 {
  var mockBLUser = new Mock<tblUser>();
  mockBLUser.Setup(mk => mk.AddUser()).Returns("success");
  var user = new BLUser(mockBLUser.Object);
  var actual = user.AddUser();
  Assert.AreEqual("success", actual);
 }  
}
   

Now you can do process on fileContent as per your requirement.

Hope this will help you and save your time.

Enjoy !!!

:)

No comments:

Post a Comment