Is there a workaround for setting [HostType(“Moles

2019-07-14 14:15发布

问题:

I'm using Pex and Moles for my low-level unit testing, but I'm also exploring MSpec for business-logic validation, and would like to keep using Moles for consistency. The problem, I think, is that MSPec uses anonymous methods, so there's no way to apply the HostType("Moles") attribute. For example:

Because of = () =>
   employeeList = EmployeeManager.GetUsersByRoles(rolesToLoad);

It should_return_a_list_of_employees = () =>
   employeeList.ShouldNotBeNull();

I'm mocking the Roles provider called inside "GetUsersByRoles," and when I try to run this test via MSpec, I get the standard "Moles requires tests to be IN an instrumented process" error, with the instruction to add [HostType("Moles")] to my test method. Is there any workaround or other option available here?

Side note: I have downloaded MSMSpec.tt and modified it to include the attribute on the generated VSTests, but I'd like to be able to run the MSpec tests directly via its own runner or TestDriven.net so I can get the friendly output for BAs and business owners.

回答1:

The workaround is to replace the anonymous method with one that is not. Moling Mspec is basically not possible.

Moles is not capable of detouring anonymous methods. The reason why is that the methods must be addressable, to be detoured. Anonymous methods are not implicitly addressable, because they are generated and referenced during runtime. Simply put, you can not call an anonymous method through the class, because it is, well... anonymous.

The Moles Manual states, "Moles can be used to detour any .NET method, including non-virtual and static methods in sealed types." Therefore, operating under the assumption that Moles uses reflection to identify class members is a safe bet. Anything that can not be called via delegate, Action, or Func, can not be moled.



标签: moles mspec