-3

Based on this Q: https://stackoverflow.com/questions/50968762/callback-not-being-called I understand (and its obvious in retrospect) what I'm doing wrong. However given the scenario as unit testing the following:

Method 1(dependency1, dependency2)

How can I test that dependency2 is called based on a condition of dependency1 and I guess more importantly should I?

Edit: to explain why this is not a duplicate of (Why) is it important that a unit test not test dependencies? I'm asking essentially given a method which gets data from a cache service unless its empty in which case it calls another service (both passed in as dependencies) should I test that the 2nd service is called given a null cache. The original q https://stackoverflow.com/questions/50968762/callback-not-being-called has more details

1 Answers1

1

Assuming you are stubbing and not mocking, you'd do it like this:

interface ICache
{
    string Data{ get; set; }
}

interface IDataSource
{
    string GetData { get; }
}

class CacheStub : ICache
{
    public string Data { get; set; }
}

class DataSourceStub : IDataSource
{
    public bool Called { get; set; } = false;
    public string GetData { get { Called = true; return "sdkjhr"; } }
}

void TestCacheMiss()
{
    //Arrange
    var o = new ClassUnderTest();
    var cache = new CacheStub { Data = null };
    var data = new DataSourceStub();

    //Act
    o.Method(cache, data);

    //Assert
    Assert.IsTrue(data.Called);
}

void TestCacheHit()
{
    //Arrange
    var o = new ClassUnderTest();
    var cache = new CacheStub { Data = "xkjhs" };
    var data = new DataSourceStub();

    //Act
    o.Method(cache, data);

    //Assert
    Assert.IsFalse(data.Called);
}

The idea here is that your stub contains a flag which gets set if a certain behavior occurs, thus indicating whether a cache miss correctly resulted in no call, or a cache hit resulted in a call. Then we assert on the flag. In these tests we are not verifying the data, so we just put in junk values for the data itself.

If you were mocking, you'd use some flavor of Isolate.Verify.WasCalled() or similar, depending on the framework.

John Wu
  • 26,462
  • Thanks John, your spot on in terms of describing what I was trying to do / the methods I was trying, in the initial question. This didn't work, I thought I was providing enough detail (as I could) to describe my issue and you've verified that.

    What I was trying to establish was, was this a pattern I should try at all.

    – Scrambledheads Jun 26 '18 at 10:29
  • Yes. This is a good unit test (as well as including several variations to test other paths). Check the logic involved in Method method, without involving external dependencies. – rediVider Dec 05 '18 at 20:56