Using Moq, how do you cheat on a method that uses local variables

New to Moq, and this is a very simple example. I want Mock to call my method "int smokeTest (int a, int b)", which is used in my method "string getCode (int someID)". Variables for smokeTest are declared and set in getCode. The problem is that when I mock the smokeTest method call, I always get the result “0” in getCode, but I want to see my predefined result “20”. The only work I found was to overload the method and pass all the variables. However, I do not want to do this because many of the methods that I want to test declare and use local variables. What is the best way to test this method with Moq? Thanks

// Example A
public string getCode(int someID)
{
    int x = 5;
    int y = 5;
    int z = _dataAccess.smokeTest(x, y);

    return _dataAccess.getCode(someID);
}

// NOTE: Doesn't work as wanted
[Test]
public void test_getCode_TestB()
{
    var x = It.IsAny<int>();
    var y = It.IsAny<int>();

    // NOTE: "20" is not returned, 0 is returned instead because local variables are used
    _mockDataAccess.Setup(m => m.smokeTest(x, y)).Returns(20);
    _mockDataAccess.Setup(m => m.getCode(234)).Returns("def345");

    var result = _businessLogic.getCode(234);

    Assert.IsTrue(result == "def345");
}

// Example B

// NOTE: Workaround - pass in variables
public string getCode(int someID, int a, int b)
{
    var c = _dataAccess.smokeTest(a, b);
    return _dataAccess.getCode(someID);
}       

[Test]
public void test_getCode_TestC()
{
    var x = It.IsAny<int>();
    var y = It.IsAny<int>();

    // NOTE: "20" is returned as wanted
    _mockDataAccess.Setup(m => m.smokeTest(x, y)).Returns(20);
    _mockDataAccess.Setup(m => m.getCode(234)).Returns("def345");

    var result = _businessLogic.getCode(234, x, y);
    Assert.IsTrue(result == "def345");
}
+4
source share
1

, It.IsAny<int>() moq:

_mockDataAccess.Setup(m => m.smokeTest(It.IsAny<int>(), It.IsAny<int>())).Returns(20);

moq, , :

int x = It.IsAny<int>();
int y = It.IsAny<int>();
_mockDataAccess.Setup(m => m.smokeTest(x, y)).Returns(20);

x y deafult int, 0, :

_mockDataAccess.Setup(m => m.smokeTest(0, 0)).Returns(20); 

moq 20, 0 0, deafult int, 0. , , It.IsAny<int>() x y, moq.

@Rob , It.IsAny<T> , moq, , , , , , T. moq.

+4

Source: https://habr.com/ru/post/1658379/


All Articles