无论如何要覆盖统一注册进行测试? [英] Anyway to override a unity registration for testing?

查看:62
本文介绍了无论如何要覆盖统一注册进行测试?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们有以下in out应用程序

We have the following in out application

container.RegisterType<IWcfCommunicationClient, Client>();

我们需要单独测试应用程序.所以我只想用模拟客户端覆盖客户端.此类将以测试模式编写写/检查SOAP请求/响应(我们有一个测试工具可以调用应用程序并自动执行 测试)

We need to test the application in isolation. So I just would like to override the client with a mockclient. This class will write the write/check the SOAP request/response in testing mode(We have a testing tool to invoke the application and do some automatic tests)

public class MockClient: IWcfCommunicationClient
{
}

应用程序中有许多针对客户端的解决方案.我不想触及已经注册了当前客户端的代码部分.我想做的是做一些技术,在测试模式下它总是使用MockClient 注册

There are many resolves for the client in the application. I don't want to touch the part of the code where it already registering the current client. What I would like to do is to do some technique where in the testing mode it always uses the MockClient registration 

所以流程可能是

container.RegisterType<IWcfCommunicationClient, MockClient>();
......
container.RegisterType<IWcfCommunicationClient, Client>();//somehow this shouldn't have any effect and the container should return MockClient even after this.

想法(即使是不同的方式)也应得到赞赏.谢谢

Ideas(even if different way) are appreciated. Thank you

推荐答案

如果您希望能够一次测试整个应用程序,恐怕您必须触摸默认位置.类型被注册(这应该在一个地方完成!),即替换(或注释掉)这个:

If you want to be able to test the entire application at once, I am afraid that you must touch the part where the default types are registered (this should be done in one single place!), i.e. replace (or comment out) this:

container.RegisterType<IWcfCommunicationClient, Client>();

...与此;

container.RegisterType<IWcfCommunicationClient, MockClient>();

但是,您通常一次编写一个类的单元测试,然后在单元测试中创建模拟对象的实例时就可以将模拟对象传递给此类(假设您当然使用了依赖注入):

However, you usually write unit tests for one class at a time and then you could just pass your mock object to this class when you create an instance of it in the unit test (assuming you use dependency injection of course):

[TestClass]
    public class CustomClassTests
    {
        [TestMethod]
        public void TestMethod1()
        {
  IWcfCommunicationClient client = new MockClient();
         CustomWpfClass classToTest = new CustomWpfClass(client);
  //peform some tests...
        }
    }


public class CustomWpfClass
{
  public CustomWpfClass(IWcfCommunicationClient client){ ... }
}

请记住将有用的帖子标记为答案和/或有用.

Please remember to mark helpful posts as answer and/or helpful.


这篇关于无论如何要覆盖统一注册进行测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆