XUnit如何对业务对象进行单元测试,我应该模拟一切吗?

时间:2018-11-12 16:54:06

标签: c# mocking xunit xunit.net

我正在尝试对我的业务对象进行单元测试(XUnit),该对象需要2个参数并在返回输出之前进行一些操作。

    public OutPutModel MyBusinessObject(InputModel1 obj1, InputModel2 obj2)
    {
        // Performing some actions here including seding a call
        // to the data access layer to perform some db operation.
        return outPutModel;
    }

在XUnit中,我正在执行以下操作

    [Fact]
    public void MyBusinessObject_ReturnsOutPutModel()
    {
        var businessObjectMock = new Mock<IBusinessObject>();
        var obj1 = new Mock<InputModel1>();
        var obj2 = new Mock<InputModel2>();

        var outPutModel = new OutPutModel();

        var result = businessObjectMock.Setup(x => x.MyBusinessObject(obj1.Object, obj2.Object)).Returns(outPutModel);

        result.Equals(outPutModel);
    }

现在,我在业务对象(公共OutPutModel MyBusinessObject(InputModel1 obj1,InputModel2 obj2))中设置了一个断点。运行测试后,它没有达到断点,但仍通过了测试。是,我在这里做错了吗?我应该模拟包括业务对象接口的所有内容,还是仅模拟参数对象并调用业务对象的新实例? 附言忘了提一下,我知道因素是在业务对象中包含数据库级的东西不是一个好主意。不幸的是,只是考虑我别无选择。

1 个答案:

答案 0 :(得分:0)

您使用的模拟框架错误。您似乎还试图模拟被测系统。

经验法则,仅模拟绝对必要的条件,并且仅在使用实现具有效果的情况下

例如,如果BusinessObject像代码注释中所指示的那样对数据访问层具有依赖性,则

public class BusinessObject: IBusinessObject{

    private readonly IDataAccess dataAccess;

    public BusinessObject(IDataAccess dataAccess) {
        this.dataAccess = dataAccess;
    }

    public OutPutModel SomeBusinessMethod(InputModel1 obj1, InputModel2 obj2) {
        // Performing some actions here including seding a call
        // to the data access layer to perform some db operation.
        var outPutModel = dataAccess.SomeMethod(obj1, obj2);

        return outPutModel;
    }
}

您将模拟被测方法中使用的依赖关系,然后调用被测类的实际实例。

例如

[Fact]
public void MyBusinessObject_ReturnsOutPutModel() {
    //Arrange
    var expected = new OutPutModel {
        // populate as needed
    }
    //mock the dependency
    var dataAccessMock = new Mock<IDataAccess>();
    //Setup the mocked dependency
    dataAccessMock
        .Setup(_ => _.SomeMethod(It.IsAny<InputModel1>(), It.IsAny<InputModel2>()))
        .Returns(expected);
    //inject the dependency into the subject under test
    var businessObject = new BusinessObject(dataAccessMock.Object);
    //needed objects for the test
    var obj1 = new InputModel1 {
        //populate as needed
    };
    var obj2 = new InputModel2 {
        //populate as needed
    };

    //Act
    var actual = businessObject.SomeBusinessMethod(obj1, obj2);

    //Assert
    Assert.AreEqual(expected, actual);
}