我的单元测试有效,但是在我添加了一些代码以从 web.config 文件中的自定义配置部分获取值后,单元测试停止工作。以下是我的代码,那些标有“//new”的行是我添加的新代码,它们破坏了测试。
public partial class AccountController : Controller
{
private readonly string _twitterConsumerKey;
private readonly string _twitterConsumerSecret;
private readonly string _twitterAccessToken;
private readonly string _twitterAccessTokenSecret;
private readonly IUserService _userService;
public AccountController(IUserService userService)
{
if (userService == null)
throw new ArgumentNullException("userService");
_userService = userService;
_twitterConsumerKey = TwitterSettings.Settings.ConsumerKey; //new code
_twitterConsumerSecret = TwitterSettings.Settings.ConsumerSecret; //new code
_twitterAccessToken = TwitterSettings.Settings.AccessToken; //new code
_twitterAccessTokenSecret = TwitterSettings.Settings.AccessTokenSecret; //new code
}
public class TwitterSettings : ConfigurationSection
{
private static TwitterSettings settings = ConfigurationManager.GetSection("Twitter") as TwitterSettings;
public static TwitterSettings Settings { get { return settings; } }
[ConfigurationProperty("ConsumerKey", IsRequired = true)]
public string ConsumerKey
{
get { return (string)this["ConsumerKey"]; }
set { this["ConsumerKey"] = value; }
}
[ConfigurationProperty("ConsumerSecret", IsRequired = true)]
public string ConsumerSecret
{
get { return (string)this["ConsumerSecret"]; }
set { this["ConsumerSecret"] = value; }
}
[ConfigurationProperty("AccessToken", IsRequired = true)]
public string AccessToken
{
get { return (string)this["AccessToken"]; }
set { this["AccessToken"] = value; }
}
[ConfigurationProperty("AccessTokenSecret", IsRequired = true)]
public string AccessTokenSecret
{
get { return (string)this["AccessTokenSecret"]; }
set { this["AccessTokenSecret"] = value; }
}
}
当我在单元测试中调用这个控制器时。我收到以下错误消息:“失败:System.NullReferenceException:对象引用未设置为对象的实例”。我需要创建一个ISSetting接口吗???
[Test]
public void Login_Action_Get_Returns_Login_View()
{
// Arrange
var expectedViewName = "~/Views/Account/Login.cshtml";
// it breaks here.
_accountController = new AccountController(_userService.Object, _mappingService.Object, _authenticationService.Object);
// Act
var result = _accountController.Login() as ViewResult;
// Assert
Assert.AreEqual(expectedViewName, result.ViewName, "View name should be {0}", expectedViewName);
}