简体   繁体   中英

How to use setup method in moq?

I can try to understand Moq and how does it work? When we should use setup method? In my opinion,its documentation is too poor.Anyway. I want to share my code and what I wanted to do.

Class under test.

  public interface IProduct
{
    bool GiveCard();
    float CalculateDiscount(decimal price, decimal discount);
}

   public class Product : IProduct
   {
    private IProduct _product;
    public string ProductName { get; set; }
    public int StockCount { get; set; }
    public float Discount { get; set; }
    public float Price { get; set; }

    public float CalculateDiscount(decimal price, decimal discount)
    {
        var discountedPrice = (price * discount) / 100;
        Discount = price - discountedPrice;
        return price - discountedPrice;
    }

     public bool GiveCard()
    {
        return CalculateDiscount(Price, Discount) > 300;
    }

}

**Unit Test Class*

[Test]
    public void GiveCard_DiscountedAmountGreaterThanOrEqual300_ReturnTrue()
    {
        var mockObject = new Mock<IProduct>();
        var productService = new Product(mockObject.Object);

        mockObject.Setup(x => x.CalculateDiscount(450, 20)).Returns(360);
        var result = productService.GiveCard();
        Console.WriteLine(result);
    }

I get 0 as a Result although I setted calculation result to the Discount property in CalculateDiscount() method .

  mockObject.Setup(x => x.CalculateDiscount(It.IsAny<int>(), It.IsAny<int>())).Returns(360);

_product object CalculateDiscount method is not used above. Hence, your mock object's setup does not get hit. You can try to this in your Product class:

public bool GiveCard()
{
    return _product.CalculateDiscount(Price, Discount) > 300;
} 

In this case, given mock object CalculateDiscount method get hit and return 360 for you.

if you use still setup like that : mockObject.Setup(x => x.CalculateDiscount(450, 20)).Returns(360); , you should supply productService.Price as 450 and productService.Discount as 20

Note: you can also assert that mockObject function get hit or not:

mockObject.Verify(mock => mock.CalculateDiscount(450,20), Times.Once());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM