我收到错误
Moq.MockException :
Expected invocation on the mock once, but was 0 times: m => m.Position = Vector
Performed invocations:
Mock<IMove:1> (m):
IMove.Position
IMove.Velocity
IMove.Position = Vector
下面是我的代码结构
using Moq;
namespace Lab1.Test
{
public class UnitTest1
{
[Fact]
public void Move_from_12_5_to_5_8_with_velocity_N7_3()
{
var move = new Mock<IMove>();
move.SetupGet(m => m.Position).Returns(new Vector( 12, 5)).Verifiable();
move.SetupGet(m => m.Velocity).Returns(new Vector( -5, 3)).Verifiable();
ICommand moveCommand = new CMove(move.Object);
moveCommand.Execute();
move.VerifySet(m => m.Position = new Vector( 5, 8), Times.Once);
move.VerifyAll();
}
}
}
和测试类
public class Vector
{
private int[] coordinates;
private int coord_cont;
public Vector(params int[] coordinates)
{
this.coordinates = coordinates;
this.coord_cont = coordinates.Length;
}
public static Vector operator +(Vector a, Vector b)
{
Vector c = new(new int[a.coord_cont]);
c.coordinates = (a.coordinates.Select((x, index) => x + b.coordinates[index]).ToArray());
return c;
}
public override bool Equals(object? obj)
{
if (obj == null || obj is not Vector)
return false;
else
return coordinates.SequenceEqual(((Vector)obj).coordinates);
}
public override int GetHashCode()
{
return coordinates.GetHashCode();
}
}
public interface IMove
{
public Vector Position { get; set; }
public Vector Velocity { get; }
}
public class CMove : ICommand
{
private readonly IMove move;
public CMove(IMove move)
{
this.move = move;
}
public void Execute()
{
move.Position += move.Velocity;
}
}
我想使用 Moq 作为界面测试的布局。但是当我尝试使用VerifySet 时,出现错误。 我尝试制作一个使用最小起订量的简单示例。 我不明白为什么模拟调用是 0 次/
我尝试在网上寻找解决方案,但没有找到类似的案例
请换行
move.VerifySet(m => m.Position = new Vector( 5, 8), Times.Once);
到
move.VerifySet(m => m.Position = new Vector(7,8), Times.Once);
因为 12 - 5 确实是 7,而不是 5 :)
我建议您在测试中使用常量,以避免将来出现相同错误的可能性。例如,您可以这样编写测试:
using Moq;
using Xunit;
using RandomThing.Core;
namespace RandomThing.Tests
{
public class UnitTest1
{
[Fact]
public void Move_from_12_5_to_5_8_with_velocity_N7_3()
{
var move = new Mock<IMove>();
var vec1 = new Vector(12, 5);
var vec2 = new Vector(-5, -3);
move.SetupGet(m => m.Position).Returns(vec1).Verifiable();
move.SetupGet(m => m.Velocity).Returns(vec2).Verifiable();
ICommand moveCommand = new CMove(move.Object);
moveCommand.Execute();
move.VerifySet(m => m.Position = vec1 + vec2, Times.Once);
move.VerifyAll();
}
}
}