I am creating a small demo app in .net core mvc.
Can anybody tell me how do i test my repository using xUnit with moq ?
Here is my Repository class :
- public interface IEmployeeRepository
- {
- bool EmployeeCrud(Employee entity);
- List
GetAllEmployees(); - }
- public class EmployeeRepository : IEmployeeRepository
- {
- private readonly SqlConnection _sqlConnection;
- public EmployeeRepository()
- {
- _sqlConnection = new SqlConnection();
- }
- public bool EmployeeCrud(Employee entity)
- {
- var dynamicParam = new DynamicParameters();
- try
- {
- if (_sqlConnection == null)
- return false;
- _sqlConnection.Open();
- dynamicParam.Add("@Id",
- entity.Id,
- DbType.Int32,
- ParameterDirection.Input);
- dynamicParam.Add("@Name",
- entity.Name,
- DbType.String,
- ParameterDirection.Input);
- _sqlConnection.Execute("spEmployeeCrud", dynamicParam, null, null,
- CommandType.StoredProcedure);
- return true;
- }
- finally
- {
- _sqlConnection.Close();
- }
- }
- public List
GetAllEmployees() - {
- var empList = new List
(); - try
- {
- if (_sqlConnection == null)
- return null;
- _sqlConnection.Open();
- var reader = _sqlConnection.ExecuteReader("spGetAllEmployees", null, null, null,
- CommandType.StoredProcedure);
- while (reader != null && reader.Read())
- {
- var items = new Employee
- {
- Id = Convert.ToInt32(reader["Id"]),
- Name = reader["Name"] .ToString()
- };
- empList.Add(items);
- }
- return empList;
- }
- finally
- {
- _sqlConnection.Close();
- }
- }
- }
How do i test this class ?
I am looking to test GetAllEmployees () for Null,NotNull and many more also how do i test my insert method i.e EmployeeCrud() ??
Here is my test class :
- public class EmployeeRepositoryTest
- {
- private IEmployeeRepository _empRepository;
- [Fact]
- public void EmployeeListShouldNotBeNull()
- {
- var mockEmpRepository = new Mock
(); - _empRepository
- = mockEmpRepository.Object;
- //now how to setup using moq and check for not null ??
- }
- }
Please not i am not using entity framework in this demo rather i am using dapper
Any help would be much appreciated.
Thanks a lot.
Replies
Know the answer? Post it — somebody with the same question will find it here.