使用 xUnit 和 Moq 验证方法是否基于条件执行
Verify with xUnit and Moq if a method was executed base on a condition
使用 xUnit 和 Moq 检查一个方法是否根据另一个方法的 return 值执行。示例:
public class A
{
public bool M1() { // return true or false ... }
public void M2() { // Do something ..... }
}
public class B
{
private A objectA;
public B(A a)
{
objectA = a;
}
public void Mb ()
{
for(int i = 0; i <= 5; i++)
{
if (objectA.M1())
{
return;
}
objectA.M2();
}
}
}
我想验证这样的事情:
[Fact]
public void Test()
{
// Arrange
Mock<A> mockA = new Mock<A>();
mockA.Setup(x => x.M1()).Return(true);
mockA.Setup(x => x.M2());
// Act
B b = new B(mockA.object);
b.Mb();
// Assert
mockA.Verify(m => m.M2(), """all exactly time that M1 returned false"""); // if this were possible it would be perfect
}
是否可以使用 xUnit 和 Moq 做类似的事情??
您应该可以这样做:
[Fact]
public void Test()
{
// Arrange
Mock<A> mockA = new Mock<A>();
int count = 0;
mockA.Setup(x => x.M1()).Returns(true).Callback(() => { count++; });
mockA.Setup(x => x.M2());
// Act
B b = new B(mockA.Object);
b.Mb();
// Assert
mockA.Verify(m => m.M2(), Times.Exactly(count), "all exactly time that M1 returned false");
}
使用 xUnit 和 Moq 检查一个方法是否根据另一个方法的 return 值执行。示例:
public class A
{
public bool M1() { // return true or false ... }
public void M2() { // Do something ..... }
}
public class B
{
private A objectA;
public B(A a)
{
objectA = a;
}
public void Mb ()
{
for(int i = 0; i <= 5; i++)
{
if (objectA.M1())
{
return;
}
objectA.M2();
}
}
}
我想验证这样的事情:
[Fact]
public void Test()
{
// Arrange
Mock<A> mockA = new Mock<A>();
mockA.Setup(x => x.M1()).Return(true);
mockA.Setup(x => x.M2());
// Act
B b = new B(mockA.object);
b.Mb();
// Assert
mockA.Verify(m => m.M2(), """all exactly time that M1 returned false"""); // if this were possible it would be perfect
}
是否可以使用 xUnit 和 Moq 做类似的事情??
您应该可以这样做:
[Fact]
public void Test()
{
// Arrange
Mock<A> mockA = new Mock<A>();
int count = 0;
mockA.Setup(x => x.M1()).Returns(true).Callback(() => { count++; });
mockA.Setup(x => x.M2());
// Act
B b = new B(mockA.Object);
b.Mb();
// Assert
mockA.Verify(m => m.M2(), Times.Exactly(count), "all exactly time that M1 returned false");
}