I have been recently working with Moles and I am now switching to Fakes. In my old test project I had a test setup, which looked like this:
[TestInitialize]
public void Setup()
{
//...
}
In there I did some necessary setup just like setting up some of my moles objects.
A test method in moles looked somehow like that (with also the [HostType("Moles")] specifying that it uses the moles objects.
[TestMethod]
[HostType("Moles")]
public void MolesTestMethod()
{
//...
}
Now, in Fakes they do not use the HostType Attribute anymore. Instead they use a ShimsContext in which you can use your "mocked" classes. It looks somehow like this:
[TestMethod]
public void FakesTestMethod()
{
using (ShimsContext.Create())
{
//...
}
}
If you do not use this context you might end up with an error message. It basically says that there was an ShimInvalidOperationException in the FakesTestMethod and you have to use the ShimsContext.Create() in the way described below)
-- C#:
using Microsoft.QualityTools.Testing.Fakes;
using(ShimsContext.Create())
{
// your test code using Shims here
}
-- VisualBasic.NET
Imports Microsoft.QualityTools.Testing.Fakes
Using ShimsContext.Create
' your test code using Shims here
End Using
So I tried to put my setup calls into that context and ended up with something like this:
[TestInitialize]
public void Setup()
{
using(ShimsContext.Create())
{
//...
}
}
Now, if I use this context in my Setup method, all the setup that is done there, will run out of context afterwards and will not be valid anymore when the unit tests are actually about to run, which is not really what I want from a test setup method.
I fixed this issue by putting the using inside the test method itself and just call a private setup method right inside this context and before the test code. This setup method now does all the handling, which before the [TestInitialize] setup method did. The code looks somehow like this:
[TestMethod]
public void PerformActionFromConfigActionStateActionIdIsSet()
{
using (ShimsContext.Create())
{
Setup();
//...
}
}
My problem with this issue is now, that this solution completely "kills" the idea of the [TestInitialize] setup method. I have to duplicate this code into EACH test method and the most important part: the objects created in this Setup() method will be created and destroyed for EACH test, which is not ideal at all!
Is there any other way to setup test data in Fakes? Any help is appreciated!