Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mocking a method within a method with FakeItEasy

How can I mock/facke the result from a function that is called in another function? Usually Test2 would be a DataAccess method that I dont like to fetch real data. What I like my unittest to test is the business logic.

This Is what I have now but its not working at all. Sum is always asserted 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 a Unittest that I would like to run on 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);
}
like image 407
Sturla Avatar asked Jan 12 '23 05:01

Sturla


1 Answers

You can't do that as far as I know.

Your instance is not an instance of the real class, just a mockup on it's interface, hence a call to instance.Test1() won't call the code you described above. You can however UnitTest Test2 Method on it's own.

What you can do however is, make 2 Unit Tests.

In the first test (Testing Method Test2), you instantiate your class with the necessary dependencies (or if there are no dependencies with certain values/parameters).

Then do a second test, with same input parameters, and Testing Test() Method.

Mockups are only used for dependencies where you have to mock up on an interface (which is instantiated outside of the class you test). i.e. if you have ClassA and ClassB and ClassA depends on IClassB interface. Then you can mock B to test A.

like image 134
Tseng Avatar answered Jan 20 '23 22:01

Tseng