I am using moq to do some unit testing on my api. However I am relatively new to mocking and am unsure on how to test or mock negative outputs. So for example I can mock creating a user and returning 200 status code, but if i try to create another user that does already exists and return a 400 then i still get 200. If i was not mocking i could do this without issue.
[TestClass]
public class UserControllerTests
{
private UserController Controller { get; }
public UserControllerTests()
{
var user = new User
{
UserName = "testuser@app.com",
Email = "testuser@app.com",
EmailConfirmed = true,
IsEnabled = true,
StripeCustomerId = Guid.NewGuid().ToString(),
StripePriceId = Guid.NewGuid().ToString(),
StripeSubscriptionId = Guid.NewGuid().ToString(),
};
var users = new List<User>
{
new()
{
UserName = "testuser1@app.com",
Email = "testuser1@app.com",
EmailConfirmed = true,
IsEnabled = true,
StripeCustomerId = Guid.NewGuid().ToString(),
StripePriceId = Guid.NewGuid().ToString(),
StripeSubscriptionId = Guid.NewGuid().ToString(),
}
};
Mock<IUserService> userService = new Mock<IUserService>();
userService.Setup(x => x.CreateUser(It.IsAny<AddUserDto>())).ReturnsAsync(IdentityResult.Success);
userService.Setup(x => x.GetUsers(It.IsAny<string>())).ReturnsAsync(users);
userService.Setup(x => x.FindUser(It.IsAny<string>())).ReturnsAsync(It.IsAny<User>());
var getUser = new GetUserDto {AllClaims = new List<string>(), Claims = new List<string>(), User = user};
userService.Setup(x => x.GetUser(It.IsAny<string>())).ReturnsAsync(getUser);
userService.Setup(x => x.DeleteUser(It.IsAny<DeleteUserDto>())).ReturnsAsync(IdentityResult.Success);
userService.Setup(x => x.EditUser(It.IsAny<EditUserDto>())).ReturnsAsync(IdentityResult.Success);
Controller = new UserController(userService.Object);
var identity = new GenericIdentity("stephen@kaizenappz.com", "test");
var contextUser = new ClaimsPrincipal(identity);
var httpContext = new DefaultHttpContext()
{
User = contextUser
};
var controllerContext = new ControllerContext()
{
HttpContext = httpContext,
};
Controller = new UserController(userService.Object)
{
ControllerContext = controllerContext,
};
}
[TestMethod]
public async Task WhenANewUserIsCreatedHttpStatusCode200ShouldBeReturned()
{
Password password = new Password();
password.NewPassword = "";
password.ConfirmPassword = "";
List<ClaimType> claimTypes = new List<ClaimType>();
ClaimType claim = new ClaimType {ClaimValue = "admin", Id = 1};
claimTypes.Add(claim);
AddUserDto model = new AddUserDto { EmailAddress = "info@kaizenappz.com", Password = password, Firstname = "Info", Surname = "Info", Claims = claimTypes, isEnabled = true };
var user = await Controller.CreateUser(model);
if (user is OkObjectResult result)
{
var actual = (HttpStatusCode)result?.StatusCode.Value;
var expected = HttpStatusCode.OK;
Assert.AreEqual(expected, actual);
}
}
}
Aucun commentaire:
Enregistrer un commentaire