0

I have a private method as below. How can I unit test this private method?

Is there a pattern that can be adopted to test these kind of private methods?

private ICart GetCart(ICart cart, IEnumerable<ILine> lines)
        {
            var discountedCart = new Cart()
            {
                Company = cart.Company,
                DiscountedSubtotal = cart.DiscountedSubtotal,
                Discounts = cart.Discounts,
                DiscountValue = cart.DiscountValue,
                Id = cart.Id,
                Items = cart.Items,

            };
            var validItems = GetValidItems(discountedCart.Items, lines);
            discountedCart.Items.Clear();
            discountedCart.Items = validItems.ToList();
            return discountedCart;
        }
GilliVilla
  • 4,998
  • 11
  • 55
  • 96
  • You can use Typemock Isolator to test private methods. You can read more about it here: [link](https://www.typemock.com/docs?book=Isolator&page=Documentation%2FHtmlDocs%2Ffakingprivatestaticmethods.htm) – JamesR Dec 31 '17 at 08:03

1 Answers1

2

You don't.

Unit testing is for testing the public interface of your code, so when the private implementation changes, you can run your tests and be sure it still works the same for the outside world. So you do not test your private methods explicitly.

You test your public methods. And you create your input data so your method gets hit in the way you want to test it. That way you test it implicitly. If it ever changes, your tests can stay the same.

Community
  • 1
  • 1
nvoigt
  • 75,013
  • 26
  • 93
  • 142
  • 2
    Apply "the duck test": "If it looks like a duck, swims like a duck, and quacks like a duck, then it probably is a duck.". You test the output. – rc_dz Dec 28 '17 at 16:58
  • Let's not forget that the need to test private methods might arise when dealing with inherited legacy code. I agree that testing private parts should be avoided when writing your own code or dealing with testable code. – Gregory Prescott Dec 31 '17 at 07:28
  • 3
    This is a wrong advice. White-box testing exists for a reason. It is fine to unit-test a private method. – Ghasan غسان Jun 30 '19 at 02:08