lundi 21 décembre 2015

How to test method1 only when it depends on method 2

Given I have a WCF service with an (example) implementation:

public interface IFoo
{
    void Bar();
    void Baz();
}

public interface ISomeDependency
{
    void DoStuff();
}

public class Foo : IFoo
{

    ISomeDependency _someDependency;

    public Foo(ISomeDependency someDependency)
    {
        this._someDependency = someDependency;
    }

    public void Bar()
    {
        // Some stuff

        _someDependency.DoStuff();

        if (1 == 1) // some condition that won't always be true
            this.Baz();
    }

    public void Baz()
    {
        // some stuff

        _someDependency.DoStuff();
    }
}

How do I go about unit testing Foo.Bars implementation without caring about the results of Foo.Baz? Specifically, I want to know that Foo.Baz(); was (or wasn't) called depending on how I'm mocking the call to Foo.Bar, but don't necessarily want Foo.Bazs logic to "fire".

I was originally thinking of doing something like this:

public class Foo : IFoo
{
    // ... same as previous

    public virtual void Baz()
    {
        // some stuff

        _someDependency.DoStuff();
    }
}

and then in my unit testing project having:

public class TestFoo : Foo
{
    public bool IsBazFired { get; private set; }

    public TestFoo(ISomeDependency someDependency)
        : base (someDependency)
    {
        IsBazFired = false;
    }

    public override void Baz()
    {
        IsBazFired = true;
    }
}

This way I can see that Foo.Baz fired in my testing (though I would have to test with TestFoo rather than Foo. Is there another way I can go about doing this? It seems like little enough work right now, but if trying to implement this all over the place, the code could/would become littered with test implementations of classes.

I don't necessarily like marking my function as virtual just so i can stub out an implementation for testing... so I'm hoping there another way.

Aucun commentaire:

Enregistrer un commentaire