我是单元测试的新手,很高兴知道我是否犯了任何错误或没有按照正确的方向前进。
情况是这样的:
我正在尝试测试一个方法(MethodUnderTest
)调用另一个方法(MethodWithAction
),它需要Action<T>
作为论据。
我想 mock MethodWithAction
, 但根据返回值测试逻辑。
结构如下:
interface IInterface
{
void MethodWithAction(Action<string> action);
}
class MyClass : IInterface
{
public void MethodWithAction(Action<string> action)
{
string sampleString = "Hello there";
action(sampleString);
}
}
class ClassUnderTest
{
public IInterface Obj = new MyClass();
public string MethodUnderTest()
{
string stringToBeTested = string.Empty;
Obj.MethodWithAction(str =>
{
if (str.Contains("."))
stringToBeTested = string.Empty;
else
stringToBeTested = str.Replace(" ", string.Empty);
});
return stringToBeTested;
}
}
我的测试方法是这样的:
[TestMethod]
[DataRow("Hello, World", "Hello,World")]
[DataRow("Hello, World.","")]
[DataRow("Hello", "Hello")]
public void MethodUnderTestReturnsCorrectString(string sampleString, string expected)
{
var mockObj = new Mock<IInterface>();
mockObj.Setup(m=>m.MethodWithAction(It.IsAny<Action<string>>))
.Callback(???);
ClassUnderTest sut = new ClassUnderTest();
sut.Obj=mockObj.Object;
string actual = sut.MethodUnderTest();
Assert.Equal(expected, actual);
}
我想知道 ???
处发生了什么在测试中,还是有完全不同的方法来解决这个问题?
最佳答案
在回调中获取传递给模拟的操作参数,并使用示例字符串调用它。
mockObj
.Setup(m => m.MethodWithAction(It.IsAny<Action<string>>))
.Callback((Action<string> action) => action(sampleString));
引用 Moq Quickstart更好地了解如何使用此模拟框架。
关于c# - 使用 Action<T> 模拟方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50586196/