FakeitEasy return null object

1.5k Views Asked by At

I made a repository class to access my DB and then I made a unit test using the FakeItEasy library. Using a real repository I got the expected result, while using the fake repository returns null.

[TestClass]
public class clientRepositoryTest
{
    [TestMethod]
    public void GetclientById()
    {
        var fakeRepository = A.Fake<IclientRepository>();
        const int expectedclient = 1;

        IclientRepository realRepository = new clientRepository();
        var realResult = realRepository.GetclientById(expectedclient); // returns expected object

        try
        {
            A.CallTo(() => fakeRepository.GetclientById(expectedclient)).MustHaveHappened();
            var fakeResult = fakeRepository.GetSupplierById(expectedSupplier); // returns null
            A.CallTo(() => fakeRepository.GetSupplierById(expectedSupplier).IdSupplier).Equals(expectedSupplier); 
        }
        catch (Exception ex)
        {
            //The current proxy generator can not intercept the specified method for the following reason:
            // - Non virtual methods can not be intercepted.
        }
    }
1

There are 1 best solutions below

0
On

Before calling any actual function call you need to make sure to call all the internal fake call like below

 A.CallTo(() => fakeRepository.GetclientById(expectedclient)).WithAnyArguments().Returns(Fakeobject/harcoded object);

Then go for the unit test call

 var fakeResult = fakeRepository.GetSupplierById(expectedSupplier); 

after that go for MustHaveHappened/ MustNotHaveHappened/Equals

A.CallTo(() => fakeRepository.GetclientById(expectedclient)).MustHaveHappened();
A.CallTo(() => fakeRepository.GetSupplierById(expectedSupplier).IdSupplier).Equals(expectedSupplier);

The Implementation should be like this

[TestClass]
    public class clientRepositoryTest
    {
        [TestMethod]
        public void GetclientById()
        {
            var fakeRepository = A.Fake<IclientRepository>();
            const int expectedclient = 1;

            IclientRepository realRepository = new clientRepository();
            var realResult = realRepository.GetclientById(expectedclient); // returns expected object

            try
            {
                A.CallTo(() => fakeRepository.GetclientById(expectedclient)).WithAnyArguments().Returns(Fakeobject/harcoded object);
                var fakeResult = fakeRepository.GetSupplierById(expectedSupplier); // returns null
        A.CallTo(() => fakeRepository.GetclientById(expectedclient)).MustHaveHappened();
                A.CallTo(() => fakeRepository.GetSupplierById(expectedSupplier).IdSupplier).Equals(expectedSupplier); 
            }
            catch (Exception ex)
            {
                //The current proxy generator can not intercept the specified method for the following reason:
                // - Non virtual methods can not be intercepted.
            }
        }