Shaksham Singh

Shaksham Singh

  • NA
  • 17
  • 6k

xUnit Test with moq

Sep 15 2018 9:53 AM
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 :
  1. public interface IEmployeeRepository  
  2. {  
  3. bool EmployeeCrud(Employee entity);  
  4. List<Employee> GetAllEmployees();  
  5. }  
  6. public class EmployeeRepository : IEmployeeRepository  
  7. {  
  8. private readonly SqlConnection _sqlConnection;  
  9.   
  10. public EmployeeRepository()  
  11. {  
  12. _sqlConnection = new SqlConnection();  
  13. }  
  14.   
  15. public bool EmployeeCrud(Employee entity)  
  16. {  
  17. var dynamicParam = new DynamicParameters();  
  18. try  
  19. {  
  20. if (_sqlConnection == null)  
  21. return false;  
  22. _sqlConnection.Open();  
  23.   
  24. dynamicParam.Add("@Id",  
  25. entity.Id,  
  26. DbType.Int32,  
  27. ParameterDirection.Input);  
  28. dynamicParam.Add("@Name",  
  29. entity.Name,  
  30. DbType.String,  
  31. ParameterDirection.Input);  
  32. _sqlConnection.Execute("spEmployeeCrud", dynamicParam, nullnull,  
  33. CommandType.StoredProcedure);  
  34.   
  35. return true;  
  36. }  
  37. finally  
  38. {  
  39. _sqlConnection.Close();  
  40. }  
  41. }  
  42.   
  43. public List<Employee> GetAllEmployees()  
  44. {  
  45. var empList = new List<Employee>();  
  46. try  
  47. {  
  48. if (_sqlConnection == null)  
  49. return null;  
  50. _sqlConnection.Open();  
  51.   
  52. var reader = _sqlConnection.ExecuteReader("spGetAllEmployees"nullnullnull,  
  53. CommandType.StoredProcedure);  
  54.   
  55. while (reader != null && reader.Read())  
  56. {  
  57. var items = new Employee  
  58. {  
  59. Id = Convert.ToInt32(reader["Id"]),  
  60. Name = reader["Name"] .ToString()  
  61. };  
  62. empList.Add(items);  
  63. }  
  64.   
  65. return empList;  
  66. }  
  67. finally  
  68. {  
  69. _sqlConnection.Close();  
  70. }  
  71. }  
  72. }  
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 :
  1. public class EmployeeRepositoryTest  
  2. {  
  3. private IEmployeeRepository _empRepository;  
  4.   
  5. [Fact]  
  6. public void EmployeeListShouldNotBeNull()  
  7. {  
  8. var mockEmpRepository = new Mock<IEmployeeRepository>();  
  9. _empRepository  
  10. = mockEmpRepository.Object;  
  11.   
  12. //now how to setup using moq and check for not null ??  
  13. }  
  14. }  
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.