Mocking a Method in FakeItEasy

How can I fake a result from a function called in another function? Normally Test2 will be a DataAccess method, which I do not like to receive real data. What I like, my unittest for testing is the business logic.

This is what I have now, but not working at all. The amount is always approved as 5!

public int Test1()
{
    var value = this.Test2(); //Unittest should substitute with 5
    var businesslogic = value + 10; //The business logic

    return businesslogic;
}

public int Test2()
{
    return 10; //I try to mock this value away in the test. Don´t go here!
}

Then I have Unittest, which I would like to run in my "business logic".

[TestMethod()]
public void TestToTest()
{
//Arrange
var instance = A.Fake<IClassWithMethods>();

      //Make calling Test2 return 5 and not 10.
A.CallTo(() => instance.Test2()).Returns(5);

      //Call the method 
var sum = instance.Test1();

//Assert if the business logic in the method works.
Assert.AreEqual(15, sum);
}
+4
source share
2 answers

First, let me say that I think that Tseng answer has some fantastic things, especially about how

  • , " " ,
  • , . , .

, :

  • Test1 return businessLogic? ( ), , Test1 5 ( 15), Test2 5.
  • TestToTest, Returns(5) Test2, Test1, , , 0, int. , 5. , :

[TestMethod]
public void TestToTestInterface()
{
    //Arrange

    var instance = A.Fake<IClassWithMethods>();

    //Make calling Test2 return 5 and not 10.
    A.CallTo(() => instance.Test2()).Returns(5);

    //Call the method 
    var sum = instance.Test1();

    //Assert if the business logic in the method works.
    Assert.AreEqual(0, sum); // because Test1 wasn't faked
}

, , ClassWithMethods, , Test1, :

  • Test1 Test2 virtual, .
  • ClassWithMethods, IClasssWithMethods.
  • , Test1 (, , Test2).

, :

public class ClassWithMethods : IClassWithMethods
{
    public virtual int Test1()
    {
        var value = this.Test2(); //Unittest should substitute with 5
        var businesslogic = value + 10; //The business logic

        return businesslogic;
    }

    public virtual int Test2()
    {
        return 10; //I try to mock this value away in the test. Don´t go here!
    }
}

[TestMethod]
public void TestToTestClass()
{
    //Arrange

    var instance = A.Fake<ClassWithMethods>();

    //Make calling Test2 return 5 and not 10.
    A.CallTo(() => instance.Test2()).Returns(5);

    // Make sure that Test1 on our fake calls the original ClassWithMethods.Test1
    A.CallTo(() => instance.Test1()).CallsBaseMethod();

    //Call the method 
    var sum = instance.Test1();

    //Assert if the business logic in the method works.
    Assert.AreEqual(15, sum);
}
+3

, .

instance , , instance.Test1() , . UnitTest Test2.

2 .

( Test2) ( /).

Test().

, ( ). .. ClassA ClassB ClassA IClassB. B, A.

+3

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


All Articles