如何测试 WCF 服务的客户端
我有一个 WCF 服务,它公开了 1 个访问数据库的方法 GetNextObjectInList(int id)
。
WCF 服务的工作原理或多或少是这样的:
public class MyService : IDisposable
{
public MyService()
{
this.IntializeDBConnection();
}
public int GetNextObjectInList(int id)
{
/* uses DB connection */
}
/* Dispose releases DB connection */
}
这使得客户端代码相对简单:
public void UseNextElementInList()
{
IMyService svc = new MyServiceClient();
int nextID = svc.GetNextObjectInList(this.ID);
/* use object */
}
我编写了单元测试来测试 WCF 服务对象,但我想测试消费者代码的各种功能,例如计时/性能/错误处理,但我不知道如何构建我的测试,以便服务不会访问数据库。
我的大多数测试(例如针对服务对象运行的测试)都会创建内存数据库,但我不知道如何让服务连接到该数据库,而无需在服务中添加特定于测试的代码。
I have a WCF service that exposes 1 method GetNextObjectInList(int id)
which hits a DB.
The WCF service works, more or less, like this:
public class MyService : IDisposable
{
public MyService()
{
this.IntializeDBConnection();
}
public int GetNextObjectInList(int id)
{
/* uses DB connection */
}
/* Dispose releases DB connection */
}
This makes the client code relatively simple:
public void UseNextElementInList()
{
IMyService svc = new MyServiceClient();
int nextID = svc.GetNextObjectInList(this.ID);
/* use object */
}
I've written unit tests to test the WCF services objects, but I'd like to test the consumer code for various things like timing/performance/error handling but I don't know how to construct my tests such that the Service doesn't hit the DB.
Most of my tests (the tests that run against the service's objects for instance) DO create an in-memory DB but I don't know how to get the service to connect to that without test-specific code in the service.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我将为您的单元测试创建一个测试服务。通常,在这些情况下我所做的是为测试项目创建一个与真实项目相同的配置,除了地址是本地主机,类型是我的测试服务类:
如果您使用的是 VS 测试项目,您可以使用ClassInitialize / ClassCleanup 属性来设置/拆除服务:
现在在 TestService 类(将实现 IMyService)内部,您可以提供测试客户端所需的任何行为,而不必担心单元测试会破坏生产代码
I would create a test service for your unit tests. Typically what I do in these circumstances is create a config for the test project that is identical to the real one except the address would be local host, and the type would be my test service class:
If you are using VS Test Project you can use the ClassInitialize / ClassCleanup attributes to set up / tear down the service:
Now inside of the TestService class (which would implement IMyService) you could provide whatever behavior necessary to test the client without worrying about your unit tests corrupting your production code