Is there a workaround for setting [HostType(“Moles”)] when dealing with anonymous methods in MSpec?

吃可爱长大的小学妹 提交于 2020-01-15 06:26:25

问题


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.



来源:https://stackoverflow.com/questions/9948119/is-there-a-workaround-for-setting-hosttypemoles-when-dealing-with-anonymou

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!