I've wri开发者_StackOverflowtten some Unit Tests using Rhino Mocks and I'm happy with the results except for the fact that I have had to expose the underlying web service as public virtual (isUserInRoleWebService) presumably because this is my stub in the partial mock. I usually use reflection to avoid exposing private methods but this will not work on the mocked object. Has anyone got around this ? Must be a common scenario.
[SetUp]
public void SetUp()
{
_mockRepository = new MockRepository();
_entitlementCache = _mockRepository.PartialMock<EntitlementCache>();
}
[Test]
// simple test to verify membership of a single role
public void Test_SingleRoleMember()
{
(new ReflectedObject(_entitlementCache)).InvokeInstanceMethod(
"setRoleHierachy",
new object[] { hierachy2Level }
);
using (_mockRepository.Record())
{
// I had to convert isUserInRoleWebService to public :-(
_entitlementCache.Stub(x => x.isUserInRoleWebService("user", "Role 1"))
.Repeat
.Once()
.Return(true);
}
using (_mockRepository.Playback())
{
bool res = _entitlementCache.IsUserInRole("user", "Role 1");
Assert.AreEqual(true, res, "user member of 'Role 1'");
}
}
[TearDown]
public void TearDown()
{
_mockRepository.ReplayAll();
_mockRepository.VerifyAll();
}
You can use partial mocks to override protected internal virtual
methods. Note that you'll need to specify [InternalsVisibleTo("YourTestProject")]
in the project-under-test's AssemblyInfo.cs.
protected internal
(or protected internal
, if you prefer) is a union of protected
and internal
. So, internal
+[InternalsVisibleTo]
makes the method visible to your test project, and protected
allows Rhino to override the virtual
method.
As a rule, I don't test or mock private methods. It seems like it might be better for you in this case to make the web service itself available as property on your cache, and then mock that. For example:
IWebService service = ...
service.Expect(s => s.IsUserInRoleWebService("user", "Role 1")).Return(true);
EntitlementCache cache = ...
cache.Service = service;
bool result = cache.IsUserInRole("user", "Role 1");
Assert.IsTrue(result, "user member of 'Role 1'");
精彩评论