【问题标题】:FluentAssertions Asserting an Exception has been thrown for an overloaded operatorFluentAssertions Asserting an Exception has been throwed for an overloaded operator
【发布时间】:2016-07-27 15:19:31
【问题描述】:

我一直在使用 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

【问题讨论】:

  • docs 不解释这个吗?
  • (例如作为操作:Action&lt;Matrix, Matrix&gt; act = (mA, mB) =&gt; { var x = mA * mB; }
  • @DavidG 我一直在查看文档,但对我来说,在这种特殊情况下我应该做什么并不清楚。你说得对,我可以这样写Action,用它代替Func,但是ShouldThrow扩展仍然无法应用。

标签: c# unit-testing fluent-assertions


【解决方案1】:

万岁,你想多了这个问题......

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-23
    • 1970-01-01
    • 2010-11-21
    • 2021-09-28
    • 2017-10-02
    • 2023-01-21
    相关资源
    最近更新 更多