manu
manu

Reputation: 1817

Unit test for private Func delegate method using MBUnit's Mirror

I would like to test the following class Private Func<> delegate method using MB Units Mirror.ForObject(). However it is not reflecting the method. Could any please provide a way to do this?

Functionality Code class

public class AccountTransaction
    {
        private static readonly Func<decimal, decimal, decimal> NetAmountCalculator = (discountedValue, discountPecentage) => discountPecentage == 100 ? 0 : Math.Round(discountedValue / (1 - (discountPecentage / 100)), 2);
    }

Test method

        /// <summary>
        /// NetAmountCalculator in normal flow
        /// </summary>
        [Test]
        public void NetAmountCalculatorTest()
        {
            var cashTransaction = Mirror.ForObject(new AccountTransaction());
            decimal discountedAmount = 90;
            decimal discountPecentage = 10;
            cashTransaction["NetAmountCalculator"].Invoke(discountedAmount , discountPecentage);
            Assert.IsTrue(true);
        }

I have referred MBUint help as well another nice help from google code

Upvotes: 2

Views: 473

Answers (1)

Yann Trevin
Yann Trevin

Reputation: 3823

NetAmountCalculator is a field of your class. It's not a method or a property, and therefore you cannot invoke it (even if it's actually a delegate so it looks like a method). What you need to do is to get the value of the field, to cast it correctly, and only then you may evaluate the result it returns.

var cashTransaction = Mirror.ForObject(new AccountTransaction());
decimal discountedAmount = 90;
decimal discountPecentage = 10;
object fieldValue = cashTransaction["NetAmountCalculator"].Value;
var func = (Func<decimal, decimal, decimal)fieldValue;
decimal actualResult = func(discountedAmount , discountPecentage);

Upvotes: 3

Related Questions