【发布时间】:2018-05-29 13:56:29
【问题描述】:
我是单元测试的新手,很高兴知道我是否犯了任何错误或没有朝着正确的方向前进。
情况如下:
我正在尝试测试一个方法 (MethodUnderTest),它调用另一个方法 (MethodWithAction),它以 Action<T> 作为参数。
我想模拟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);
}
我想知道测试中???的位置是什么,或者这个问题有完全不同的方法吗?
【问题讨论】:
-
你最好在 CodeReview.StackExchange 上问这个
标签: c# .net unit-testing mocking moq