开发者

Why does setting Log on a DataContext cause an ObjectDisposedException?

开发者 https://www.devze.com 2023-03-07 00:15 出处:网络
This is my service class: public class MyService { private readonly MyDataContext _db; public MyService()

This is my service class:

public class MyService
{
  private readonly MyDataContext _db;

  public MyService()
  {
    _db =开发者_Go百科 new MyDataContext(GetConnectionString());
#if DEBUG
    _db.Log = Console.Error;
#endif
  }

  public void Get(int id)
  {
    return from item in _db.Items
           where item.Id == id
           select item;
  }
}

This is my test class

[TestClass]
public class MyServiceTest
{
  private MyService _service = new MyService();

  [TestMethod]
  public void CanGetSomething()
  {
     var something = _service.Get(1).ToList();
     // Asserts
  }

  [TestMethod]
  public void CanGetSomethingElse()
  {
    var somethingElse = _service.Get(2).ToList();
    // Commented out everything else.
  }
}

Running CanGetSomething and CanGetSomethingElse separately using the ReSharper 5 test runner works fine, both tests pass. However, trying to run the tests in succession by running the entire class causes the first method to pass and the second method to throw the exception

System.ObjectDisposedException: Cannot write to a closed TextWriter.

It doesn't seem to matter what method I call in the second test, anything that calls _db will cause the error. Commenting out _db.Log = Console.Error gets rid of the exception, and it will work fine.

I'd like to be able to log the error and run an entire class of tests at once, but I can't figure out why it is behaving like this.

Any ideas?


Dont share members of your test class! Not knowing resharper, but VS 2010 UnitTesting is really kean on cleaning up after running a test. My assumption for what happens here is when constructing your TestClass, your context is being initialized. And after running a single test. Resharper cleans up the resources, therefore also disposing your context.

Use a TestInitialize to create a new instance of your dataContext, therefore isolating your tests from one another

0

精彩评论

暂无评论...
验证码 换一张
取 消