简体   繁体   中英

Write unit test cases in VS2012

I'm new to write unit test cases using VS2012.

Can someone help me to write unit test cases for below method?

public myclasstype getEmployeeById(int empid)
{
    // this method will return employee objects
}

Just a general outline of what you can test on the GetEmployeeById method:

[TestMethod]
public void GetEmployeeById_Id_Employee()
{
   Employee employee = mockManager.MockObject<Employee>().Object;
   employee.DateOfBirth = new DateTime(1970, 1, 1, 0, 0, 0);

   using (RecordExpectations recorder = new RecordExpectations())
   {
     var dataLayer = new DataLayer();
     recorder.ExpectAndReturn(dataLayer.GetEmployeeById(1), employee);
   }

   var company = new Company();
   Employee result = company.GetEmployeeById(1);
   Assert.AreEqual(result.DateOfBirth, employee.DateOfBirth);
}

It's a pretty broad question, but lets say you have an Employee class...

public class Employee
{
   private IEmployeeRepository _repo;
   public Employee(IEmployeeRepository repo)
   {
    _repo = repo;
   }

   public Employee GetEmployeeById(int empid)
   {
      return _repo.GetEmployeeById(empid);
   }
}

Your Test would then need to be something like...

[Test]
public void Employee_GetEmployee_By_Id()
{
   IEmployeeRepository repo = new FakeEmployeeRepository();
   var employeeClass = new Employee(repo);
   var employee = employee.GetEmployeeById(1);

   //verify employee detail
 }

This is very basic, but gives you an idea. Obviously, you will have a Fake Employee Repository which will just return a pre-setup Employee, and in production you will have a real implementation of IEmployeeRepository which will connects to a DB for example.

public interface IEmployeeRepository 
{
   Employee GetEmployeeById(int id);
}

public class FakeEmployeeRepository : IEmployeeRepository 
{
   public Employee GetEmployeeById(int id)
   {
     return new Employee { ... };
   }
}

This is all hand typed, so there's probably errors here...it's just to give an idea though.

  1. Right clik on the method you want to write unit test for > Create UnitTest...
  2. In Create Unit Test dialog
  3. Tick off which methods you want to generate unit tests for:
  4. [OK]
  5. Enter a name for the test project
  6. [Create]

Use Assert class to check the results

Below are the steps 1. Add Unit test project, Solution explorer -> Add -> New Project -> Select Test from the template -> Unit Test project. 2. Download and add Reference to the Moq library you can do that by Nuget command below. To Get Nuget Package manager console, go to Tools Menu-> Library Package Manager Console -> Library Package Manager. This should show Nuget package manager console near to debug, error window.

install-package Moq

While hitting above command make sure that you have selected your test project on the project list on Nuget Package manager console.

  1. Lets say you have defined classes as below

     public class Employee 

    { public int Id { get; set; }

     public string Name { get; set; } 

    }

    public interface IEmployeeRepository { Employee GetById(int id); }

    public interface IUnitOfWork { T GetById(int id) where T : new() ; }

    public class UnitOfWork : IUnitOfWork { // Implementation of IUnitOfWork

     //public T GetById<T>(int id) where T: new(); //{ // return new T(); //} 

    }

    public class EmployeeRepository : IEmployeeRepository { //You are injecting Unit Of Work here public IUnitOfWork UnitOfWork { get; set; }

     public Employee GetById(int id) { // Making call to database here; return UnitOfWork.GetById<Employee>(id); } 

    }

  2. Add UnitTest to your UnitTest Project by right click on Unit Test project , Add -> Unit Test. Below is sample code for your Unit Test based on your classes above.

    using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq;

namespace UnitTestProject1 { [TestClass] public class EmployeeUnitTest { Mock _unitOfWork; IEmployeeRepository _employeeRepository;

    //This will be called before each test
    [TestInitialize]
    public void SetUp()
    {
        _unitOfWork = new Mock<IUnitOfWork>();
        _employeeRepository = new EmployeeRepository();
    }

    [TestMethod]
    public void GetById_ShouldCallUnitOfWork()
    {
        //Arrange
        const int Id = 1;
        _unitOfWork.Setup(x => x.GetById<Employee>(It.IsAny<int>())).Verifiable();

        //Act
        _employeeRepository.GetById(Id);

        //Assert
        _unitOfWork.Verify(x => x.GetById<Employee>(Id), Times.Once());
    }

    [TestMethod]
    public void GetById_ShouldRetrunEmployee()
    {
        //Arrange
        const int Id = 1;
        var expectedEmp = new Employee { Id = Id, Name= "Emp"};

        _unitOfWork.Setup(x => x.GetById<Employee>(It.IsAny<int>())).Returns(expectedEmp) ;

        //Act
        var employee = _employeeRepository.GetById(Id);

        //Assert
        Assert.AreEqual(expectedEmp, employee);
    }

}

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM