如何模拟一个不断变化的 class ?
How to mock a class that is constantly changing?
我有一个 class XrmServiceContext,每次 CRM 配置更改时它都会更改。
我的服务 class 在其构造函数中接受它:
public class fooService(XrmServiceContext xrmServiceContext)
{
//implementation
}
我需要模拟 XrmServiceContext 以便为我的单元测试设置预期并验证行为。
如何模拟此 class 以便在我的 fooService 测试中定义行为?
XrmServiceContext
应被视为第 3 方 API。
从服务和wrap/adapt实现中的上下文中创建所需功能的抽象。
public interface IXrmServiceContext {
//api endpoints you want
}
因此,与其传递具体的服务上下文,不如将抽象传递给您的服务。
public class fooService {
public fooService (IXrmServiceContext xrmServiceContext){
}
//implementation
}
这将使设置预期和验证单元测试的行为变得容易得多。
我会通过在 XrmServiceContext
的构造函数中创建一个伪造的 IOrganizationService
对象来做到这一点,我建议使用:https://github.com/jordimontana82/fake-xrm-easy. You can learn more about how to use FakeXrmEasy, personally I found it very easy, by looking at https://dynamicsvalue.com/get-started/overview.
以下是根据您的目的使用该库的简要概述:
var context = new XrmFakedContext();
context.ProxyTypesAssembly = Assembly.GetAssembly(typeof(Account));
//You'll need to setup this fake to have the data necessary to support your use cases for XrmServiceContext.
var account = new Account() { Id = Guid.NewGuid(), Name = "My First Faked Account yeah!" };
context.Initialize(new List<Entity>() {
account
});
var service = context.GetFakedOrganizationService();
using (var context = new XrmServiceContext(service))
{
//Create instance of fooService class
var testableFooService = new fooService(context);
//TODO: Run your test.
}
我有一个 class XrmServiceContext,每次 CRM 配置更改时它都会更改。
我的服务 class 在其构造函数中接受它:
public class fooService(XrmServiceContext xrmServiceContext)
{
//implementation
}
我需要模拟 XrmServiceContext 以便为我的单元测试设置预期并验证行为。
如何模拟此 class 以便在我的 fooService 测试中定义行为?
XrmServiceContext
应被视为第 3 方 API。
从服务和wrap/adapt实现中的上下文中创建所需功能的抽象。
public interface IXrmServiceContext {
//api endpoints you want
}
因此,与其传递具体的服务上下文,不如将抽象传递给您的服务。
public class fooService {
public fooService (IXrmServiceContext xrmServiceContext){
}
//implementation
}
这将使设置预期和验证单元测试的行为变得容易得多。
我会通过在 XrmServiceContext
的构造函数中创建一个伪造的 IOrganizationService
对象来做到这一点,我建议使用:https://github.com/jordimontana82/fake-xrm-easy. You can learn more about how to use FakeXrmEasy, personally I found it very easy, by looking at https://dynamicsvalue.com/get-started/overview.
以下是根据您的目的使用该库的简要概述:
var context = new XrmFakedContext();
context.ProxyTypesAssembly = Assembly.GetAssembly(typeof(Account));
//You'll need to setup this fake to have the data necessary to support your use cases for XrmServiceContext.
var account = new Account() { Id = Guid.NewGuid(), Name = "My First Faked Account yeah!" };
context.Initialize(new List<Entity>() {
account
});
var service = context.GetFakedOrganizationService();
using (var context = new XrmServiceContext(service))
{
//Create instance of fooService class
var testableFooService = new fooService(context);
//TODO: Run your test.
}