我有一个这样的通用存储库:
public class GenericRepository<TEntity> : IRepository<TEntity> where TEntity : class
{
private readonly DbContext _context;
private DbSet<TEntity> _dbSet;
public GenericRepository(DbContext context)
{
_context = context;
_dbSet = context.Set<TEntity>();
}
public virtual async Task<IEnumerable<TEntity>> Get(Expression<Func<TEntity, bool>> filter = null, Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null,
string includeProperties = "")
{
IQueryable<TEntity> query = _dbSet;
if (filter != null)
{
query = query.Where(filter);
}
foreach (var includeProperty in includeProperties.Split
(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
{
query = query.Include(includeProperty);
}
if (orderBy != null)
{
return await orderBy(query).ToListAsync<TEntity>();
}
return await query.ToListAsync<TEntity>();
}
}
通用工作单元如下:
public class GenericUnitOfWork<TContext> : IUnitOfWork<TContext>, IDisposable where TContext : DbContext
{
#region Private Member Variables
private TContext _context = null;
private Dictionary<Type, object> _repositories = new Dictionary<Type, object>();
#endregion
#region Constructors
public GenericUnitOfWork(TContext context)
{
_context = context;
}
#endregion
#region Public Properties
public TContext Context
{
get
{
return _context;
}
}
#endregion
#region Public Methods
public IRepository<TEntity> Repository<TEntity>() where TEntity : class
{
if (_repositories.Keys.Contains(typeof(TEntity)))
{
return _repositories[typeof(TEntity)] as GenericRepository<TEntity>;
}
GenericRepository<TEntity> repo = new GenericRepository<TEntity>(_context);
_repositories.Add(typeof(TEntity), repo);
return repo;
}
}
和一个UserService:
public class UserService : IUserService
{
private readonly IUnitOfWork<TASConfigDBContext> _unitOfWork;
private readonly IJwtFactory _jwFactory;
private readonly ITokenFactory _tokenFactory;
public UserService(IUnitOfWork<TASConfigDBContext> unitOfWork, IJwtFactory jwtFactory, ITokenFactory tokenfactory)
{
_unitOfWork = unitOfWork;
_jwFactory = jwtFactory;
_tokenFactory = tokenfactory;
}
public bool IsUserAuthenticated(string userName, string password)
{
var user = _unitOfWork.Repository<Users>().GetQuery().Where(x => string.Equals(x.Name, userName.Trim(), StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault();
// ensure we have a user with the given user name
if (user != null && user.Password == password)
{
return true;
}
return false;
}
}
AuthController:
public class AuthController : ControllerBase
{
#region Private Member Variables
private readonly IUserService _userService;
private readonly ILogger<AuthController> _logger;
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="AuthController"/> class.
/// </summary>
/// <param name="userService">userService DAL layer.</param>
/// <param name="logger">nlog logger.</param>
public AuthController(IUserService userService, ILogger<AuthController> logger)
{
_userService = userService;
_logger = logger;
}
#endregion
#region Public Methods
/// <summary>
/// Returns true if login is successful.
/// </summary>
/// <remarks>
/// Sample login:
///
/// POST /auth/login
/// {
/// "Username": "administrator",
/// "Password": ""
/// }.
///
/// </remarks>
/// <param name="login">The username and password.</param>
/// <returns>returns a token for validated user.</returns>
/// <response code="200">Success: Returns a token for a validated user.</response>
/// <response code="400">Bad request.</response>
/// <response code="401">Unauthorized: username and password doesn't match.</response>
[AllowAnonymous]
[HttpPost("login")]
[EnableCors("AllowOrigin")]
[Produces("application/json")]
[ProducesResponseType(typeof(ResponseMessage), 200)]
[ProducesResponseType(typeof(ResponseMessage), 400)]
[ProducesResponseType(typeof(ResponseMessage), 401)]
public async Task<ActionResult> Post([FromBody] LoginModel login)
{
HttpStatusCode statusCode;
ActionResult response;
ResponseMessage tokenResponseMessage;
ResponseToken responseToken;
if (login == null)
{
tokenResponseMessage = new ResponseMessage(false, null, new Message(HttpStatusCode.BadRequest));
_logger.LogError($"The Login model is null. {(LoginModel)null}");
response = BadRequest(tokenResponseMessage);
}
else if (!ModelState.IsValid)
{
var errors = new Hashtable();
foreach (var pair in ModelState)
{
if (pair.Value.Errors.Count > 0)
{
errors[pair.Key] = pair.Value.Errors.Select(error => error.ErrorMessage).ToList();
}
}
tokenResponseMessage = new ResponseMessage(false, errors, new Message(HttpStatusCode.BadRequest));
_logger.LogError($"The ModelState is invalid. {errors} ");
response = BadRequest(tokenResponseMessage);
}
else
{
if (_userService.IsUserAuthenticated(login.UserName, login.Password))
{
_logger.LogInformation($"Returned with valid username: {login.UserName}");
responseToken = await _userService.GetResponseToken(login.UserName);
_logger.LogInformation($"Response token generated for: {login.UserName}");
statusCode = HttpStatusCode.OK;
tokenResponseMessage = new ResponseMessage(true, responseToken, new Message(statusCode));
// generate access token
response = Ok(tokenResponseMessage);
}
else
{
_logger.LogWarning($"No username for userid : {login.UserName} found");
statusCode = HttpStatusCode.Unauthorized;
tokenResponseMessage = new ResponseMessage(false, null, new Message(statusCode, "Incorrect username or password"));
response = Unauthorized(tokenResponseMessage);
}
}
return response;
}
现在,我正在尝试使用Moq进行单元测试:
public async void PostReturnsOkWhenLoginSucceeds()
{
Mock<IJwtFactory> jwtFactory = new Mock<IJwtFactory>();
Mock<ITokenFactory> tokenFactory = new Mock<ITokenFactory>();
_logger = Mock.Of<ILogger<AuthController>>();
int userId = 13;
//Arrange
var user = new Users
{
UserId = 13,
Name = "administrator",
Password = "test123",
Active = 1,
Rights = -1,
UserGuid = Guid.Parse("7ED0E003-45EF-4C93-B89F-05BF5047F151")
};
var userRepositoryMock = new Mock<GenericRepository<Users>>();
userRepositoryMock.Setup(m => m.GetById(userId)).Returns(user).Verifiable();
var unitOfWorkMock = new Mock<IUnitOfWork<MyConfigDBContext>>();
unitOfWorkMock.Setup(m => m.Repository<Users>()).Returns(userRepositoryMock.Object);
IUserService sut = new UserService(unitOfWorkMock.Object, jwtFactory.Object, tokenFactory.Object);
_controller = new AuthController(sut, _logger);
var result = await _controller.Post(new LoginModel("administrator", "test123")).ConfigureAwait(false);
// assert
var statusCode = ((ContentResult)result).StatusCode;
Assert.True(statusCode.HasValue && statusCode.Value == (int)HttpStatusCode.OK);
}
此返回Unauthorized而不是Ok。请提出建议,因为我觉得存储库已空。
答案 0 :(得分:5)
仅模拟必要的依赖关系,以使受测对象得以完成。
例如,您的测试可以简化为
public async Task Post_Should_Return_Ok_WhenLoginSucceeds() {
//Arrange
var logger = Mock.Of<ILogger<AuthController>>();
var user = new Users {
UserId = 13,
Name = "administrator",
Password = "test123",
Active = 1,
Rights = -1,
UserGuid = Guid.Parse("7ED0E003-45EF-4C93-B89F-05BF5047F151")
};
var login = new LoginModel(user.Name, user.Password);
var userService = new Mock<IUserService>();
userService
.Setup(_ => _.IsUserAuthenticated(login.UserName, login.Password))
.Returns(true);
userService
.Setup(_ => _.GetResponseToken(login.UserName))
.ReturnsAsync(user);
var controller = new AuthController(userService.Object, logger);
//Act
var result = await controller.Post(login);
//Assert
var statusCode = ((ContentResult)result).StatusCode;
Assert.True(statusCode.HasValue && statusCode.Value == (int)HttpStatusCode.OK);
}