我正在使用MVC架构构建web应用程序。我将需要使用一个仍在开发中的web服务(我们遵循敏捷方法)。web服务有几个方法。几个方法是稳定的(已发表)运行),一些方法仍在开发中。
所以这意味着,从客户端,我需要模拟新方法(直到它们准备好),并继续使用旧方法(用于回归测试)。
在方法级别模拟服务的最佳实践是什么?欢迎提出任何建议或想法。我可以使用任何mock框架吗?
我要在ASP上应用这个。Net MVC框架以及基于CodeIgniter构建的PHP应用程序。
可能有很多方法可以做到这一点。这就是我的工作。它可能属于也可能不属于"最佳实践"的范畴。
我写了一个带有web服务接口的包装器。
假设我们的WebService有四个方法,Get()
, Create()
, Update()
, Delete()
。
我的界面很简单
public interface IServiceWrapper
{
object Get();
object Create(object toCreate);
object Update(object toUpdate);
bool Delete(object toDelete);
}
现在我可以有两个实现。一个调用实际的web服务
public class ServiceWrapper : IServiceWrapper
{
public object Get(){//call webservice Get()}
public object Create(object toCreate){//call webservice Create()}
public object Update(object toUpdate){//call webservice Update()}
public bool Delete(object toDelete){//call webservice Delete()}
}
和一个假的(或模拟)实现,我模仿web服务的行为(通常在内存数据)
public class FakeServiceWrapper : IServiceWrapper
{
private void PopulateObjects()
{
//mimic your data source here if you are not using moq or some other mocking framework
}
public object Get(){//mimic behavior of webservice Get()}
public object Create(object toCreate){//mimic behavior of webservice Create()}
public object Update(object toUpdate){//mimic behavior of webservice Update()}
public bool Delete(object toDelete){//mimic behavior of webservice Delete()}
}
通常我会通过向消费服务或控制器注入实例来使用其中一个或另一个。但是,如果您愿意,您可以很容易地实例化每个包装器的实例,并在方法级别上"挑选"。
由于我使用依赖注入,我们无法在Mock &方法层面的实际服务。换句话说,我们需要使用或者 Mock 或者 RealTime服务。
参照上面的例子,
我将从RegisterUnityMapping
切换IServiceWrapper
的Mock或真实实现。
在我的开发团队中这是一个可行的方法。而在本地开发环境中,当我有时切换到Mock来运行几个单元测试时——否则,总是使用真正的实现。无需多言,在更高的环境中-只使用真实实现。
Som