amnesia
amnesia

Reputation: 1988

How to unit test public behavior dependent on private state?

I need to unit test a public interface method of a class, but the defined behavior is dependent on a private state variable. Something like this:

private enum _state;

public void Connect()
{
    if (_state == AlreadyConnected)
        throw Exception;

    (... do more things ...)
}

In this case I want to ensure the proper exception is thrown if the method is called when the state is already a specific value, but how can I set this up if the state field is private?

Upvotes: 0

Views: 95

Answers (1)

alex.b
alex.b

Reputation: 4567

In your case private state represents the result of actions performed on entity and its reaction on the actions.
So, test will look like:

[Test]
public void Connect_throws_exception_if_already_connected()
{
       var foo = new Foo();
       foo.Connect();


       Exception thrownExc = null;

       try
       {
            foo.Connect();
       }
       catch(InvalidOperationException exc)
       {
           thrownExc = exc;
       }

       Assert.IsNotNull(thrownExc, "It was expected to get exception on 2nd connect attempt, but nothing were thrown.");
}

Upvotes: 2

Related Questions