我有一些与SendGrid服务相关的appsetting,如用户名,密码和一些resetpasswordemail设置。现在我想在我的单元测试中使用它们。我的ResetPasswordSetting类看起来像这样。
public class ResetPasswordEmailSetting : IResetPasswordEmailSetting
{
public string ResetPasswordEmailUrl { get; set; }
public List<string> AddToEmails { get; set; }
public string FromEmail
{
get { return ConfigurationManager.AppSettings.Get("ResetPassword_FromEmail"); }
}
public string Subject
{
get { return ConfigurationManager.AppSettings.Get("ResetPassword_Subject"); }
}
public string SenderDisplayName
{
get { return ConfigurationManager.AppSettings.Get("ResetPassword_SenderDisplayName"); }
}
}
当我使用此类运行我的单元测试时,从Webconfig appsetting部分获取其值的字段将为空。
我的单元测试看起来像这样。
[TestMethod]
[TestCategory("SendGrid-Service")]
public async Task email_recieved_when_correct_email_provided()
{
var sendgrid = new SendGridService();
var resetpasswordsetting = new ResetPasswordEmailSetting
{
AddToEmails = new List<string> { "fluffyduk@gmail.com" },
ResetPasswordEmailUrl = "www.google.com",
};
// when i debug then resetpasswordsetting fields are coming null other then above.
var result = await sendgrid.SendResetPasswordEmail(resetpasswordsetting, new
SendGridSettings());
result.Should().BeTrue();
}
所以任何想法如何在单元测试中获得这些设置。
答案 0 :(得分:3)
我想到的第一件事是,在此测试中,您对设置不感兴趣,测试的主题是来自SendResetPasswordEmail
类的SendGridService
方法。请记住,您正在实施UNIT测试,而不是集成测试或类似的测试。在进行单元测试时,您应该努力隔离任何依赖项,并且配置设置是您的类实际上不需要测试特定业务逻辑的依赖项。为此,您应该创建一个模拟对象,因为再次,不需要配置设置来测试一个功能。
但是,如果您仍然坚持使用真实的配置文件,那么没有什么可以阻止您将app.config
文件添加到您的单元测试项目并指定您的测试所需的所有appSettings