3

I've got a class with a private collection _blockRegister, and a method that mutates this collection RegisterBlockType:

public class FileBlocksParser
{
    private readonly Dictionary<uint, IFileBlockParser> _blockRegister = new Dictionary<uint, IFileBlockParser>();

    public void RegisterBlockType(IFileBlockParser blockParser)
    {
        if (!_blockRegister.ContainsKey(blockParser.BlockType))
        {
            _blockRegister.Add(blockParser.BlockType, blockParser);
        }
    }

    ....
 }

I've come to unit testing this class, and it seems pretty logical to test whether registering a block type works. However, it's acting only on a private field. I don't want to make the field public, as that would expose it to being made invalid. I'm not sure there's a real reason to add some way of retrieving registered blocks, except for the sake of testing that blocks have been added in the unit tests.

What would be best-practice for testing a method like this that has no measurable (immediate) impact out-side of the class?

  1. Add in a public GetRegisteredBlockTypes method just for testing.

  2. Use reflection or similar to check private field (brittle? I shouldn't really care how it's being registered internally... Which leads me to 3.)

  3. Or should I not test it at all? Ultimately, if it's not registering them, the class would fail the later unit tests (testing the other functionality of the class would require a mock IFileBlockParser to be registered, so it would fail)

1

The typical recommendation is to "not test your privates" and instead prefer to test side effects that are visible through the public API.

If there were a bug in the RegisterBlockType method, how would you notice it?

Once you know the answer to that, you should be able to identify which parts of the public API you can use to assert the expected behaviour.

  • Yeah I think this is the conclusion I've come to. The side-effect of RegisterBlockType not working is when you try 'parse' a block of a type you've registered, it wouldn't return a block of that type. So I've added something to test for that with the parse method. – Joe Nov 4 '17 at 18:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.