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

我有一个Matrix类(此示例已简化),并带有一个重载的乘法运算符:

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没有通用ShouldThrowFunc扩展方法,而且我不确定是否将其包装在Action中。是否可以在这种情况下以这种方式使用FluentAssertions,或者以其他方式使用FluentAssertions,还是必须使用ExpectedExceptions

最佳答案

Hooray对问题的思考过多...

像这样编写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");
}

09-11 20:17