gpt4 book ai didi

c# - Moq - 为构造函数注入(inject)对象创建模拟实例

转载 作者:太空狗 更新时间:2023-10-30 01:05:12 24 4
gpt4 key购买 nike

问题

我想为 Credentials 类创建一个单元测试,在执行 Calculate() 方法后验证给定凭据的密码是否等于由实现 IPasswordCalculator 接口(interface)的对象。

实际上,我创建的模拟对象在调用 Calculate(ICredentials) 方法时返回 string.Empty 值,而不是 Pa$$w0rd,那将是期望的返回。

然后...

  • 如何在无需手动创建 stub 类的情况下实现此测试?
  • 如何在模拟对象上定义回调方法以始终返回 Pa$$w0rd

提前致谢。

代码

IPasswordCalculator 接口(interface)

/// <summary>
/// The password calculator interface.
/// </summary>
public interface IPasswordCalculator
{
/// <summary>
/// Calculates the user password using
/// <paramref name="credentials"/> instance.
/// </summary>
/// <param name="credentials">
/// <see cref="ICredentials"/> to perform the calculation.
/// </param>
void Calculate(ICredentials credentials);
}

ICredentials 接口(interface)

/// <summary>
/// The Credentials interface.
/// </summary>
public interface ICredentials
{
/// <summary>
/// Gets or sets the user password.
/// </summary>
string Password { get; set; }

/// <summary>
/// Gets the user name.
/// </summary>
string Username { get; }

/// <summary>
/// Calculates the password.
/// </summary>
void Calculate();
}

凭证实现

/// <summary>
/// User credentials.
/// </summary>
public sealed class Credentials : ICredentials
{
/// <summary>
/// Initializes a new instance of the <see cref="Credentials" /> class.
/// </summary>
/// <param name="passwordCalculator">
/// The credentials calculator.
/// </param>
/// <param name="username">
/// The user name.
/// </param>
public Credentials(IPasswordCalculator passwordCalculator, string username)
{
this.Calculator = passwordCalculator;
this.Username = username;
this.Password = string.Empty;
}

/// <summary>
/// Calculates the password.
/// </summary>
public void Calculate()
{
if (null != this.Calculator)
{
this.Calculator.Calculate(this);
}
}
}

测试

    /// <summary>
/// Calculate should set password value expected using calculator.
/// </summary>
[TestMethod]
public void CalculateShouldSetPasswordValueExpectedUsingCalculator()
{
ICredentials credentials = null;
var repo = new MockRepository(MockBehavior.Default);
var mock = repo.Create<IPasswordCalculator>();
mock.Setup(x => x.Calculate(credentials))
.Callback(() => { credentials.Password = "Pa$$w0rd"; });

IPasswordCalculator calculator = mock.Object;

credentials = new Credentials(calculator, "Me");
credentials.Calculate();

Assert.AreEqual("Pa$$w0rd", credentials.Password); // Fail
}

最佳答案

您需要按以下方式设置模拟

mock.Setup(x => x.Calculate(It.IsAny<ICredentials>()))
.Callback((ICredentials c) => { c.Password = "Pa$$w0rd"; });

因此你告诉它“无论你得到什么 ICredentials 作为 Calculate 方法的参数,将它的 Password 设置为 'Pa$$word '"

关于c# - Moq - 为构造函数注入(inject)对象创建模拟实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19811934/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com