What should I consider when choosing a mocking framework for .Net

后端 未结 8 1998
梦如初夏
梦如初夏 2020-12-12 18:20

There are lots of mocking frameworks out there for .Net. There is no clear winner that has superseded the others in every way. The leading mocking frameworks also have many

8条回答
  •  隐瞒了意图╮
    2020-12-12 18:42

    What should I consider when choosing a mocking framework for .Net

    Another aspect to consider, besides the design of the code base that you are testing, is how readable your tests are when using mocks.

    In this regard, I am putting in a vote for NSubstitute - one of the newer mocking frameworks with a very expressive API (no lambdas) and comparable functionality with Moq and Rhino Mocks. It has recently reached version 1.0.

    A usage example (from the NSubstitute homepage):

    //Create:
    var calculator = Substitute.For();
    
    //Set a return value:
    calculator.Add(1, 2).Returns(3);
    Assert.AreEqual(3, calculator.Add(1, 2));
    
    //Check received calls:
    calculator.Received().Add(1, Arg.Any());
    calculator.DidNotReceive().Add(2, 2);
    
    //Raise events
    calculator.PoweringUp += Raise.Event();
    

    A detailed comparison of the readability of tests using RhinoMocks, Moq and NSubstitute is given here.

提交回复
热议问题