我的單元測試工作,但在我添加了一些代碼來從web.config文件中的自定義配置部分獲取值後,單元測試停止工作。以下是我的代碼,那些標有「// new」的行是我添加的新代碼,並且它們打破了測試。在web.config文件中的自定義配置節打破我的單元測試
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:對象引用未設置爲對象的實例」。我是否需要創建一個ISetting接口?
[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);
}
感謝您回答我所有的單元測試問題。現在在這之後,我覺得我使用它非常舒服。 – qinking126 2012-07-23 16:05:50