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

标签 c# unit-testing fluent-assertions

我一直在使用 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 没有用于通用 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");
}

关于c# - FluentAssertions 断言已为重载运算符抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36464385/

相关文章:

c# - WebApi 2 中的单元测试 IAuthenticationFilter

c# - FluentAssertions Should.Equal 在集合上,包含空值

c# - Should().Contain() 具有等效选项

.net - WebAPI 中的单元测试操作参数

unit-testing - XCTest 失败,出现异常 'Non-UI clients cannont be autopaused'

c# - OR 条件的流利断言

javascript - 如何使盒子像盒子碰撞器一样工作

c# - 是否可以在不强制转换的情况下在 C# 中实现 "virtual constructor"模式?

c# - 异步 FTP 上传

c# - 访问匿名类型变量