Perché impostare il log on a DataContext causa un oggettoDiseconexception?
-
15-11-2019 - |
Domanda
Questa è la mia classe di servizio:
public class MyService
{
private readonly MyDataContext _db;
public MyService()
{
_db = 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;
}
}
.
Questa è la mia classe di test
[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.
}
}
.
Esecuzione di CanGetSomething
e CanGetSomethingElse
separatamente utilizzando il runner di test ReshArper 5 funziona bene, entrambi i test passano.Tuttavia, cercando di eseguire i test in successione eseguendo l'intera classe cause il primo metodo di passare e il secondo metodo per lanciare l'eccezione
.System.ObjectDisonospeaxception: impossibile scrivere su un textWriter chiuso.
Non sembra importante quale metodo chiamo nel secondo test, tutto ciò che chiama
_db
causerà l'errore.Commentando_db.Log = Console.Error
si libera dell'Eccezione e funzionerà bene.Mi piacerebbe essere in grado di registrare l'errore ed eseguire un'intera classe di test contemporaneamente, ma non riesco a capire perché si sta comportando in questo modo.
Qualche idea?
Soluzione
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