zoukankan      html  css  js  c++  java
  • C# Unit test(1)

    Mock

    Example:

    var paymentServiceMock = new Mock<IPaymentService>();
    

    A Mock can be:

    • Instructed, you can tell a mock that if a certain method is called then it can answer with a certain response
    • Verified, verification is something you carry out after your production code has been called. You carry this out to verify that a certain method has been called with specific arguments

    Instruct our Mock

    To instruct it we use the method Setup() like so:

    paymentServiceMock.Setup(p => p.Charge()).Returns(true)
    

    we need to give the Charge() method the arguments it needs. There are two ways we can give the Charge() method the arguments it needs:

    1. Exact arguments, this is when we give it some concrete values like so:
    var card = new Card("owner", "number", "CVV number");
    
    paymentServiceMock.Setup(p => p.Charge(114,card)).Returns(true)
    
    1. General arguments, here we can use the helper It, which will allow us to instruct the method Charge() that any values of a certain data type can be passed through:
    paymentServiceMock.Setup(p => p.Charge(It.IsAny<double>(),card)).Returns(true)
    

    Accessing our implementation

    We will need to pass an implementation of our Mock when we call the actual production code. So how do we do that?

    There's an Object property on the Mock that represents the concrete implementation. Below we are using just that. We first construct cardMock and then we pass cardMock.Object to the Charge() method.

    var cardMock = new Mock<ICard>();
    
    paymentServiceMock.Setup(p => p.Charge(It.IsAny<double>(),cardMock.Object)).Returns(true)
    

    Example

    [Test]
    public void DoWorkTest()
    {
        // Set up the mock
        myInterfaceMock.Setup(m => m.DoesSomething()).Returns(true);
        myInterfaceMock.SetupGet(m => m.Name).Returns("Molly");
    
        var result = subject.DoWork();
    
        // Verify that DoesSomething was called only once
        myInterfaceMock.Verify((m => m.DoesSomething()), Times.Once());
    
        // Verify that DoesSomething was never called
        myInterfaceMock.Verify((m => m.DoesSomething()), Times.Never());
    }
    
  • 相关阅读:
    SQL-W3School-高级:SQL ALIAS(别名)
    SQL-W3School-高级:SQL BETWEEN 操作符
    SQL-W3School-高级:SQL IN 操作符
    SQL-W3School-高级:SQL 通配符
    C语言实现定积分求解方法
    android使用webview上传文件(支持相册和拍照)
    POJ2349+Prim
    nyist 740 “炫舞家“ST(动态规划)
    paip.php eclipse output echo 乱码
    Deep Learning论文笔记之(八)Deep Learning最新综述
  • 原文地址:https://www.cnblogs.com/francisforeverhappy/p/CsharpUnitTest1.html
Copyright © 2011-2022 走看看