P
P
PickGG2018-03-04 11:59:38
C++ / C#
PickGG, 2018-03-04 11:59:38

How to test methods that work with private or protected fields?

There is such a simple code.

class Worker { }

    interface IOffice
    {
        void AddWorker(Worker worker);
        Worker[] GetWorkers();
    }

    class Office : IOffice
    {
        private List<Worker> _workers;

        public Office()
        {
            _workers = new List<Worker>();
        }

        public void AddWorker(Worker worker)
        {
            _workers.Add(worker);
        }

        public Worker[] GetWorkers()
        {
            return _workers.ToArray();
        }

How to test the AddWorker method to add items? To do this, I need to get a list of Workers in the test.
Which option to choose?
  1. Through the call to GetWorkers will not work, I will test two methods at once - this is bad.
  2. If I make the _workers field as internal then encapsulation will be broken
  3. Get field through reflection
  4. Maybe there is a better option?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
E
eRKa, 2018-03-04
@kttotto

1. Not true. You will use GetWorkers but test AddWorker. You can write a separate test on GetWorkers.
PS: Testing private fields is bad practice. You need to test the expected behavior of the accessible from outside the method, i.e. public. You do not need to test the internal implementation, you need to test what it will give as an output.

A
Alexander Yudakov, 2018-03-04
@AlexanderYudakov

Don't use CLR, C# and computer.
You should only use AddWorker.
Do it on paper. Fountain pen. With ink.

A
Andrew K., 2018-03-04
@gdi32dll

Yes, in any test I will need the _workers field. How to get it?

No way. To put it bluntly, this code is impossible to test. Therefore, for example, static classes are not used in TDD. Test-driven development makes you think first of all what you write. Why do we need an Office class wrapper around the List class? What tasks does she solve? Why not just use the List class in the place where the IOffice interface will be used? When you start thinking about such things, then there is no need to access private fields.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question