Showing posts with label Unit Test. Show all posts
Showing posts with label Unit Test. Show all posts

.Net Core : Unit Test with NUnit

.Net Core : Unit Test with NUnit


Below example is implemented with Nunit test to test .net core project feature.

Create test class,

namespace DotNetCoreDemo.Test
{
    public class EmployeeServiceTest
    {
        
    }
}

OneTimeSetUp 

 IEmployeeService employeeService;
        public Mock<IEmployeeRepository> mockEmployeeRepository;
        
        [OneTimeSetUp]
        public void Init()
        {
            mockEmployeeRepository = new Mock<IEmployeeRepository>();
            employeeService = new EmployeeService( this.mockEmployeeRepository.Object);
        }

Data Sources for test cases,

static object[] employeeSource =
        {
            new object[]
            {
                new Employee[]
                {
                    new Employee()
                    {
                        Id = 1, Name = "demo1", Email = "demo1@demo.com"
                    },
                    new Employee()
                    {
                        Id = 2, Name = "demo2", Email = "demo2@demo.com"
                    }
                } 
            }
        };

        static object[] employeeSourceNull =
        {
            new object[]
            {
                new Employee[]
                {
                    
                }
            }
        };

Test for get data,

 [Test, TestCaseSource("employeeSource")]
        public void GetEmployeeList_Return_True(Employee[] employees)
        {
            //Init            
            mockEmployeeRepository.Setup(p => p.GetAllEmployee()).Returns(employees.AsQueryable().ToList());
            
            //Act
            List<Employee> result  = employeeService.GetAllEmployee().ToList();

            ////Assert
            Assert.Greater(result.Count, 0);
        }

Test for no data,

[Test, TestCaseSource("employeeSourceNull")]
        public void GetEmployeeList_NoData_Return_True(Employee[] employees)
        {
            //Init            
            mockEmployeeRepository.Setup(p => p.GetAllEmployee()).Returns(employees.AsQueryable().ToList());

            //Act
            List<Employee> result = employeeService.GetAllEmployee().ToList();

            ////Assert
            Assert.AreEqual(result.Count, 0);
        }


Hope this will help you and save your time.

Enjoy !!!

:)

Test discovery or execution might not work for this project

Error: Test discovery or execution might not work for this project.'


Issue

Message=Test discovery or execution might not work for this project. It's recommended to reference NuGet test adapters in each test project in the solution.

 

Solution

If you are using MS Test, try installing

MSTest.TestAdapter via nuget

if you are using nunit, install

NUnit3TestAdapter latest versions via nuget.

  
After installing please restart the visual studio and then you can see the tests running.

Hope this will help you and save your time.

Enjoy !!!

:)

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 !!!

:)

Mock unit testing

Mock unit testing 



Mock unit testing is very useful for developer, but my point of view its fake unit testing, its making us foolish.
Lets see how it is...

I have created on console application in visual studio and try to explain two cases as below...

Case1

Case1: I have created Case1 folder in "UnitTestCaseProject" and write below two classes. 

namespace UnitTestCaseProject.Case1
{
    public class checkEmployee
    {
        public virtual Boolean checkEmp()
        {
            throw new NotImplementedException();
            //return true;
        }
    }
}

namespace UnitTestCaseProject.Case1
{
    public class processEmployee
    {
        public bool insertEmployee(checkEmployee objtmp)
        {
            objtmp.checkEmp();
            return true;
        }
    }
}

Case2

I have created Case2 folder in "UnitTestCaseProject" and write below three classes.

namespace UnitTestCaseProject.Case2
{
    public interface IGetDataRepository
    {
        string GetNameById(int id);
    }
}

namespace UnitTestCaseProject.Case2
{
    public class EmployeeRepository : IGetDataRepository
    {
        public string GetNameById(int id)
        {
            string name;
            if (id == 1)
            {
                name = "Excellent";
            }
            else if (id == 2)
            {
                name = "Expert";
            }
            else
            {
                name = "Not Found";
            }
            return name;
        }
    }
}

namespace UnitTestCaseProject.Case2
{
    public class Implementation1
    {
        private readonly IGetDataRepository _data;
        public Implementation1(IGetDataRepository data)
        {
            _data = data;
        }

        public string GetNameById(int id)
        {
            return _data.GetNameById(id);
        }
    }
}


Test Project

Now, I have added new test project in solution with name "UnitTestCaseProject.Test" and write unit test cases for above two cases.


I have installed "Moq" packages using manage nuget packages...

namespace UnitTestCaseProject.Test
{
    [TestClass]
    public class Case1Test
    {
        [TestMethod]
        public void insertEmployeeTestSuccess()
        {
            Mock<checkEmployee> chk = new Mock<checkEmployee>();
            chk.Setup(x => x.checkEmp()).Returns(true);

            processEmployee obje = new processEmployee();
            Assert.AreEqual(obje.insertEmployee(chk.Object), true);
        }
    }
}


namespace UnitTestCaseProject.Test
{
    [TestClass]
    public class Cast2Test
    {
        [TestMethod]
        public void TestMethod2()
        {
            var mock = new Mock<IGetDataRepository>();
            mock.Setup(p => p.GetNameById(1)).Returns("demo");
            Implementation1 home = new Implementation1(mock.Object);
            string result = home.GetNameById(1);
            Assert.AreEqual("demo", result);
        }
    }
}


While I run the above two unit test cases, it gives me success result.


Real Implementation and usage

Now, below code is actual implementation in our project "UnitTestCaseProject".

namespace UnitTestCaseProject
{
    class Program
    {
        static void Main(string[] args)
        {
            processEmployee processEmployee = new processEmployee();
            checkEmployee checkEmployee = new checkEmployee();
            var result = processEmployee.insertEmployee(checkEmployee);
            Console.WriteLine(result);
        }
    }
}



Now, if I run the project it gives me an error in actual usage, that should not give me any error while I already tested with unit test cases. So, you can see that it is not useful in our real project or application.

I suggest while you deploy project or application in Live environment, then we should write test cases with test environment.


Hope this will help you and save your time.

Enjoy !!!

:)