问题
I have a static class which creates a database class instance. I am looking for a way to shim/stub that database class in my tests.
public partial class Y : Form
{
static Models.DBModel db = new Models.DBModel();
....
Unfortunately I cannot change the code. Is there any way I can mock this database class in my tests?
回答1:
This worked for me:
I. Update yourdll.fakes
to include:
...
<ShimGeneration>
<Clear/>
...
<Add FullName="Models.DBModel"/>
...
</ShimGeneration>
...
II. In your TestClass
create method with [TestInitialize]
and [TestCleanup]
attribute:
using Models.Fakes;
IDisposable shimsContext;
[TestInitialize]
public void SetUp()
{
shimsContext = ShimsContext.Create();
ShimDBModel.Constructor = (@this) =>
{
ShimDBModel shim = new ShimDBModel(@this)
{
// here you can provide shim methods for DBModel
};
};
}
[TestCleanup]
public void CleanUp()
{
// Let's do not forget to clean up shims after each test runs
shimsContext.Dispose();
}
III. And finally in your test, the Y.db
should be Shim created in SetUp
method.
[TestMethod]
public void Test()
{
Y.db... // db should be shim
}
来源:https://stackoverflow.com/questions/34122823/shimming-a-class-instantiated-by-a-static-class