I'm trying to setup test for the login controller but it fails whenever I run the test. I'm getting the error below. var result in should_Login() is always null.
Message: Expected: not null But was: null
Stack Trace:
UserTests.should_Login() line 47
GenericAdapter`1.GetResult()
AsyncToSyncAdapter.Await(Func`1 invoke)
TestMethodCommand.RunTestMethod(TestExecutionContext context)
TestMethodCommand.Execute(TestExecutionContext context)
<>c__DisplayClass1_0.<Execute>b__0()
BeforeAndAfterTestCommand.RunTestMethodInThreadAbortSafeZone(TestExecutionContext context, Action action)
//UserTests
public class UserTests
{
Mock<IUserService> UserServiceMock = new Mock<IUserService>();
private UserController UserController;
[SetUp]
public void Setup()
{
UserServiceMock.Setup(x => x.Authenticate(new UserRequest { Email = "[email protected]", Password = "Password1" }))
.ReturnsAsync(new ApiResponse(HttpStatusCode.OK)
{
ResponseObject = new
{
User = new
{
Id = 1,
Name = "Test",
Email = "[email protected]",
Token = "TokenGen"
}
}
});
}
[Test]
public async Task should_Login()
{
UserController = new UserController(UserServiceMock.Object);
var result = await UserController.Authenticate(
new UserRequest { Email = "[email protected]", Password = "Password" });
Assert.IsNotNull(result);
Assert.AreEqual(200, result.HttpResponseCode);
}
}
The user controller looks as follows
public class UserController : ControllerBase { private IUserService _userService; public UserController(IUserService userService) { _userService = userService; }
[AllowAnonymous]
[HttpPost("authenticate")]
public Task<ApiResponse> Authenticate([FromBody] UserRequest userRequest)
{
try
{
return _userService.Authenticate(userRequest);
}
catch (Exception ex)
{
var response = new ApiResponse(HttpStatusCode.InternalServerError) { ResponseMessage = ex.Message };
return Task.Run(() => response);
}
}
}