我正在對 WebAPI 控制器使用 xUnit 測驗。我的控制器中有以下方法:
public string GetLoginMessage()
{
var loginMessage = GetSystemSetting("LoginMessage", "Retrieving...");
return loginMessage;
}
public string GetOwnerName()
{
string ownerName = GetSystemSetting("OwnerName", "Retrieving...");
return ownerName;
}
private string GetSystemSetting(string SettingName, string DefaultValue)
{
var settingValue = DefaultValue;
//var _systemSettingsBL = new SystemSettingsBL();
var systemSettingInfoList = _systemSettingsBL.GetSystemSettings(0, 0);
var setting = systemSettingInfoList.Where(w => w.Key == SettingName).FirstOrDefault();
if (setting != null && string.IsNullOrWhiteSpace(setting.Value) == false)
{ settingValue = setting.Value; }
return settingValue;
}
如您所見,GetSystemSettings() 被同一控制器中的各種方法多次呼叫。
我在這里使用 GetLoginMessage() 和 GetOwnerName() 的簡單示例。假設這三種方法應該單獨測驗,我的邏輯是否正確?如果是這樣,我不需要模擬 GetSystemSettings()。如果是這樣,我該怎么做?
到目前為止我的測驗:
public class AccountsControllerTests : BaseUnitTest
{
private readonly Mock<ICommonBL> _commonBLMock;
private readonly Mock<ISystemSettingsBL> _systemSettingsBLMock;
private readonly AccountsController _accountsController;
public AccountsControllerTests()
{
_commonBLMock = new Mock<ICommonBL>();
_systemSettingsBLMock = new Mock<ISystemSettingsBL>();
_accountsController = new AccountsController(_commonBLMock.Object, _systemSettingsBLMock.Object);
}
[Fact]
private void GetLoginMessage_ShouldReturnString_WhenCalled()
{
//how to possibly mock local controller method GetSystemSetting()
var loginMessage = _accountsController.GetLoginMessage();
Assert.NotNull(loginMessage);
Assert.IsType<string>(loginMessage);
}
}
uj5u.com熱心網友回復:
您的測驗場景取決于_systemSettingsBL.GetSystemSettings擁有資料并對其進行驗證。所以你應該專注于模擬它,你可以通過定義GetSystemSettingson的 setup 方法來做到這一點_systemSettingsBLMock。有了它,您可以根據您的模擬資料添加斷言。loginMessage
在您的測驗方法 GetLoginMessage_ShouldReturnString_WhenCalled 中,設定如下
_systemSettingsBLMock.Setup(
s => s.GetSystemSettings(It.IsAny<int>(), It.IsAny<int>())
.Returns( //return here the mock object of systemSettingInfoList which contains LoginMessage settingName );
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/494598.html
