fearofawhackplanet
fearofawhackplanet

Reputation: 53406

Unit test when class has dependency on protected property of base class

public class MyBaseClass
{
    protected void OnSomeEvent(EventContext context)
    {
         SomeType  = _someService.DoSomeLogic(context);
    }

    public SomeType SomeType { get; private set; } 
}

MyBaseClass works some magic to initialise a public property value when an event is triggerd in the process pipline.

public class MyClass : MyBaseClass
{
    public string Foo()
    {
        if (SomeType.SomeLogic())
            throw new InvalidOpertaionException();

        return "huzzah";
    }
}

The flow in other classes depends on SomeType being initialised.

How can I unit test MyClass.Foo()?

[TestMethod]
public void Foo_ReturnsHuzzah()
{
    var result = new MyClass().Foo(); 
    Assert.IsHuzzah(result);   
}

Upvotes: 0

Views: 581

Answers (3)

Jason Meckley
Jason Meckley

Reputation: 7591

Set SomeType before calling Foo()

Upvotes: 0

Austin Salonen
Austin Salonen

Reputation: 50235

This type of temporal coupling (the event must be raised before the call to Foo is valid) is often considered a design flaw so the first thing I would do is revisit the design to make sure what I have is right.

If you don't want to go that route, the easiest solution is to initialize SomeType with a Null Object implementation of SomeType like so...

class NullSomeType : SomeType
{
    public override bool SomeLogic() { return false; }
}

Then you default SomeType with the Null Object in the constructor.

public MyBaseClass()
{
   SomeType = new NullSomeType();
}

Upvotes: 2

Joon
Joon

Reputation: 2147

_someService looks like an external dependency. I would use Dependency Injection to make that external dependency injectable, and then use a mocking framework to inject something that returns state that will make the rest of your tests pass.

Then run the public method that ultimately invokes OnSomeEvent, and you can test the whole chain of processing

Upvotes: 3

Related Questions