我有一种情况,我正在运行单元测试并调用Verify
来断言使用非空列表作为参数调用方法。被测试的方法调用方法末尾列表中的Clear()
。似乎当Verify
被调用时,它在当前时间检查列表的状态,而不是在我的函数被调用的时候。这是预期的行为吗?是否有任何方法可以让Verify
在调用我的方法时使用列表的值?
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using System.Linq;
using System.Collections.Generic;
namespace Tests
{
[TestClass]
public class UnitTest1
{
public interface IMyDependency
{
void ParseNumbers(List<int> numbers);
}
public class MyDependency : IMyDependency
{
public void ParseNumbers(List<int> numbers)
{
}
}
public class SystemUnderTest
{
private IMyDependency myDependency;
public SystemUnderTest(IMyDependency myDependency)
{
this.myDependency = myDependency;
}
public void DoSomething(List<int> numbers)
{
this.myDependency.ParseNumbers(numbers);
// This causes my test to fail because Verify thinks that ParseNumbers was called
// with an empty list as the parameter, even though the list was not empty when
// ParseNumbers was called
numbers.Clear();
}
}
[TestMethod]
public void TestMethod1()
{
var myDependency = new Mock<IMyDependency>();
var systemUnderTest = new SystemUnderTest(myDependency.Object);
systemUnderTest.DoSomething(new List<int> { 1, 2, 3 });
// This succeeds
myDependency.Verify(e => e.ParseNumbers(It.IsAny<List<int>>()), Times.Once);
// This fails
myDependency.Verify(e => e.ParseNumbers(It.Is<List<int>>(m => m.Count > 0)), Times.Once);
}
}
}
这是预期的行为吗
看起来这个行为可能是一个bug。我建议向开发人员提出一个问题。
是否有任何方法可以让验证在调用我的方法时使用列表的值?
设置Verifiable
[TestMethod]
public void TestMethod1() {
// Arrange
var myDependency = new Mock<IMyDependency>();
myDependency
.Setup(e => e.ParseNumbers(It.Is<List<int>>(m => m.Count > 0)))
.Verifiable(); //<-- MAKE SETUP VERIFIABLE
var systemUnderTest = new SystemUnderTest(myDependency.Object);
// Act
systemUnderTest.DoSomething(new List<int> { 1, 2, 3 });
// Assert
myDependency.Verify(); // Verifies that all verifiable expectations have been met.
}