1
我嘗試爲我的控制器編寫一些單元測試。如何測試apicontroller?
[HttpPost]
public Answer RegistrationSocial([FromBody] RegistrationSocialRequest newUser)
{
var answer = new Answer();
try
{
userProvider.RegistrationSocial(newUser.Email,
newUser.PhoneNumber,
newUser.SocialProviderId,
newUser.SocialProvider,
UserIP);
answer.Result = 0;
}
catch (Exception e)
{
answer.Result = 2;
answer.Description = "Server error";
}
return answer;
}
private string UserIP
{
get { return HttpContext.Current.Request.UserHostAddress; }
}
RegistrationSocialRequest只是模型綁定所需的POCO對象。這個方法返回json,我想跟蹤它的變化,只是爲了確保客戶端可以使用它。爲了測試,我使用Moq和MSTest。這是測試方法。
[TestMethod]
public void IsJsonOkRegistrationSocial()
{
//Arrange
Mock<IUserProvider> mock = new Mock<IUserProvider>();
mock.Setup(m => m.RegistrationSocial("[email protected]",
"123",
"0987654321",
1,
"192.0.0.1"));
UserController controller = new UserController(mock.Object);
Answer answerOk = new Answer
{
Result = 0,
Caption = "Ok",
Description = null,
Data = null
};
//Action
var answer = controller.RegistrationSocial(new RegistrationSocialRequest
{
SocialProvider = 1,
Email = "[email protected]",
PhoneNumber = "123",
SocialProviderId = "0987654321"
});
//Assert
Assert.AreEqual(JsonConvert.SerializeObject(answerOk),
JsonConvert.SerializeObject(answer));
}
但是引發異常的方法,因爲UserIP爲空,我不能理解爲什麼。我是單元測試新手,也許這一切都可以以更簡單的方式完成。
也許一些工程,但這個解決方案是工作。謝謝。 – Arthur