插件调试的一般方法是附加CRM进程,这种方式最原始,最方便也最不方便,说它最方便呢是单人独立开发的时候操作起来效率最高,说他不方便呢是多人开发的时候你附加了CRM进程后CRM就直接死掉了导致其他人不能用,针对多人开发这种场景呢又引入了第二种调试方式profiler,如果有人没听过这种方式的可以去搜下,这里就不都做介绍了。
本篇要讲的是第三种调试方式,借助单元测试工具RhinoMocks,该工具nuget上就有
我的demo中主要用到两个project,一个叫action的plugin项目,一个叫RhinoMocks的unittest项目
前者的新建就不多说了,后者的新建是这样的,Add project—Test—Unit Test
Unit Test 项目需要引用如下assembly,第一个红框就是我们的plugin,第二第三个是CRM的SDK,第四个就是RhinoMocks,通过nuget下载即可
Unit Test项目中的测试代码如下,取了一条客户数据作为demo,代码最后一行调用插件execute
public void TestMethod1()
{
ClientCredentials clientCredentials = new ClientCredentials();
clientCredentials.Windows.ClientCredential = new System.Net.NetworkCredential(username,pwd, domain);
IServiceProvider serviceProvider = MockRepository.GenerateMock<IServiceProvider>();
IPluginExecutionContext context = MockRepository.GenerateMock<IPluginExecutionContext>();
IOrganizationServiceFactory factory = MockRepository.GenerateMock<IOrganizationServiceFactory>();
IOrganizationService service = MockRepository.GenerateMock<IOrganizationService>();
service = new OrganizationServiceProxy(new Uri("http://121.40.75.24:5555/origin/XRMServices/2011/Organization.svc"), null, clientCredentials, null);
ParameterCollection paramBag = new ParameterCollection();
Entity currentent = service.Retrieve("account", new Guid("79E0EBB1-5B4E-E611-9419-9C49FE150FAC"), new Microsoft.Xrm.Sdk.Query.ColumnSet(true));
paramBag.Add("Target", currentent);
context.Stub(x => x.InputParameters).Return(paramBag);
serviceProvider.Stub(x => x.GetService(typeof(IPluginExecutionContext))).Return(context);
serviceProvider.Stub(x => x.GetService(typeof(IOrganizationServiceFactory))).Return(factory);
factory.Stub(x => x.CreateOrganizationService(null)).Return(service);
//调用插件,将封装好的serviceProvider传进去
Action.Class1 test = new Action.Class1();
test.Execute(serviceProvider);
}
然后调试unint test项目
进入插件,看下获取到的account实体数据
当然你也可以不先调试,用这个方式来单元测试你的代码是否存bug,比如下面这种常见的关键字不在字典中的,该方法可以在你注册插件之前使用,将一些显而易见但又可能被我们忽略的bug提示出来,大大的提高了编程效率。
方法虽好,但也有其局限性不是所有的场景都能用的,所以我们常说没有最好的方法,只有最合适的方法,什么样的场景采用什么样的方法。
本文参考博客:
http://www.krely.cn/archives/89
http://blog.csdn.net/ghostbear/article/details/8032068