FluentAssertions 断言已为重载运算符抛出异常

FluentAssertions Asserting an Exception has been thrown for an overloaded operator

我一直在使用 FluentAssertions 进行单元测试,并开始研究断言是否正确抛出异常。我知道我可以使用 ExpectedExceptions 方法属性,但如果可能的话,我想学习 FluentAssertion 方法。

我有一个带有重载乘法运算符的 Matrix class(针对此示例进行了简化):

public class Matrix
{
    public int Rows { get; set; }
    public int Columns { get; set; }
    public float[,] Elements { get; set; }

    public static Matrix operator *(Matrix m1, Matrix m2)
    {
        if (m1.Columns != m2.Rows)
        {
            throw new Exception("These matrices cant be multiplied");
        }

        return new Matrix(1, 2, new float[,] { {1, 2} });
    }
}

我想测试异常情况。这是我目前所拥有的:

[TestMethod]
//[ExpectedException(typeof(Exception), "These matrices cant be multiplied")]
public void MatrixMultiplication_IncorrectMatrixSize_ExceptionTest()
{
    // Arrange
    var elementsA = new float[,]
    {
        {4, 7},
        {6, 8}
    };

    var elementsB = new float[,]
    {
        {3, 0},
        {1, 1},
        {5, 2}
    };

    Matrix A = new Matrix() {Rows=2, Columns=2, Elements=elementsA);
    Matrix B = new Matrix() {Rows=3, Columns=2, Elements=elementsB);

    // Act
    Func<Matrix, Matrix, Matrix> act = (mA, mB) => mA * mB;

    // Assert
    act(A,B).ShouldThrow<Exception>().WithInnerMessage("These matrices cant be multiplied");
}

我遇到的问题是 FluentAssertions 没有通用 FuncShouldThrow 扩展方法,我不确定是否或如何将其包装在 Action 中.在这种情况下是否可以以这种方式使用 FluentAssertions,或者我是否以不同的方式使用 FluentAssertions,或者我必须使用 ExpectedExceptions?

为问题想得太多而万岁...

像这样编写 TestMethod 使其工作:

[TestMethod]
public void MatrixMultiplication_IncorrectMatrixSize_ExceptionTest()
{
    // Arrange
    var elementsA = new float[,]
    {
        {4, 7},
        {6, 8}
    };

    var elementsB = new float[,]
    {
        {3, 0},
        {1, 1},
        {5, 2}
    };

    Matrix A = new Matrix() {Rows=2, Columns=2, Elements=elementsA);
    Matrix B = new Matrix() {Rows=3, Columns=2, Elements=elementsB);

    // Act
    Action act = () => { var x = A * B; };

    // Assert
    act.ShouldThrow<Exception>().WithMessage("These matrices cant be multiplied");
}