问题
I am wondering is there any alternative lib to the shim feature provided in Microsoft fake framework since it is only supported in ultimate version?
回答1:
There are three frameworks to my knowledge that allow you to mock non virtual methods and sealed classes like Fakes' Shims. There are
- Microsofts' Moles or Fakes
- Teleriks JustMock
- TypeMocks
They are all commercial because they use the Profiling API, which is very hairy and poorly documented, so coding them is a real pain.
And for the record I'm all for fakes. Most code that people are working on is legacy code. One of the Pragmatic Programmer's rules of refactoring is make sure that you have unit test coverage before any refactorings to avoid regression. This makes Fakes and similar frameworks super useful, especially when the legacy code was not written for test-ability.
回答2:
Prig hasn't been updated to work with VS 2017, but Pose does, and works really well for what I needed it for (basic shimming of Environment.UserName
, and DateTime.Now
and similar), and has a really nice interface:
// Create shims. They only apply within this isolate block.
var dateTimeShim = Shim.Replace(() => DateTime.Now)
.With(() => new DateTime(2010, 1, 1));
var usernameShim = Shim.Replace(() => Environment.UserName)
.With(() => "john.wick");
// Shims are only active within an Isolate block - and you
// have to pass all shims you want to be active.
PoseContext.Isolate(() =>
{
// Run your test - shims are active at this point.
RunTest();
}, dateTimeShim, usernameShim);
EDIT
I should note that I get lots of errors when doing fairly basic tests - really scary errors like "Common Language Runtime detected an invalid program.", and "JIT Compiler encountered an internal limitation." so caveat emptor.
回答3:
An open source alternative is Prig. MIT licenced and still active - but slightly behind with VS IDE
回答4:
Yes and for a detailed comparison look here:
Mock framework vs MS Fakes frameworks
As you will learn from Jim Cooper's answer the Fake assemblies are actually a bad thing and there are much better alternatives, e.g. which support refactoring and require less code (use generics).
来源:https://stackoverflow.com/questions/19031984/any-alternative-to-shim-feature-provided-in-microsoft-fake-framework