Вопрос

I have found that it's significant easier to test a class if you inherit from it. consider this seudo example:

  public class Bizz
  {
    public void Do()
    {
      var obj = ExtenOutOfTest();
      someList.Add(obj);
    }

    protected List<ISomeObejct> someList = new ISomeObejct<ISomeObejct>();

    protected virtual ISomeObejct ExtenOutOfTest()
    {
     //return real obejct 
    }
  }

and the test would look like this:

  [TestClass]
  public class BizzTest : Bizz
  {
    private ISomeObejct _fakedObj;

    protected override ISomeObejct ExtenOutOfTest()
    {
      return _fakedObj;
    }

    [TestMethod]
    public void Test_Do_Add()
    {
      _fakedObj = new Fake<ISomeObejct>().FakedObject; 

      Assert.IsFalse(someList.Any());
      base.Do(); //<-- target
      Assert.IsTrue(someList.Any());
    }
  }

Now I have the ability to isolate my test, and my Bizz object dosn't exposes any other methods except the ones is was supposed to.

Is this way of unittesting bad practice?

When I modify my Bizz class to implement IDisposable I can no longer run my test:

~Bizz(){Dispose(false);}

public void Dispose()
{
  Dispose(true);
}

private void Dispose(bool disposing)
{
  if(!disposing) return;
  //do cleanup resources
}

It won't even start before showing me that it failed: Unit Test Adapter threw exception: Ambiguous match found.

I have tried to make Dispose virtual and then override it in the test class - but it didn't work.

Any help is appreciated.

Это было полезно?

Решение

Using the standard dispose pattern as described, e.g., in http://msdn.microsoft.com/en-us/library/fs2xkftw(v=vs.100).aspx fixes the problem. That is, replace private void Dispose(bool disposing)... by protected void Dispose(bool disposing)....

The problem is related to fact that MSTest (I tested Visual Studio 2010 and 2013) does call dispose on the test class after each tests. To this end, MSTest queries all public void Dispose functions but unfortunately ignores the argument, which is the part of the function signature that distinguishes your two variants. As a result, MSTest exists with Ambiguous match found.

Другие советы

The reason for the failer is still a mysteryfor me. but this seemed to fixet up:

void IDisposable.Dispose()
{
  GC.SuppressFinalize(this);
  Dispose(true);
}

private void Dispose(bool disposing)
{
   //actual cleanup omitted
}

Notes that the interface is now implermented explictly + the actual cleanup method Dispose(bool disposing) is made private.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top