使用结构图通过依赖注入进行单元测试 [英] Unit test with Dependency Injection using struture map

查看:59
本文介绍了使用结构图通过依赖注入进行单元测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是MVC和IoC以及其他相关概念的新手.

I am new to MVC and IoC and other related concepts.

我必须为一个旧项目编写单元测试用例.它使用结构图进行依赖注入.我使用的第三方dll公开了一些接口.现在,我必须为控制器类中的方法编写单元测试用例.

I have to write unit test cases for an old project. It uses Structure Map for Dependecy Injection. Third party dlls that I use expose some interfaces. Now I have to write unit test cases for methods in the controller class.

控制器的构造函数如下:

The constructor of controller looks like this:

HomeController(IClientData clientdata)
{
    _clientdata = clientdata;
}
//The clientdata was initialized

在我的测试案例中,如何初始化控制器类和接口,例如 IClientData ?将 IClientData clientdata 传递给构造函数时说:将类型作为var 传递.

In my test case, how do I initialize the controller class and interface like IClientData? Passing IClientData clientdata to constructor says: passing type as var.

如何初始化/模拟 IClientData 中的数据?我不知道该接口是如何在dll中实现的.

How do I initialize/mock the data in IClientData? I don't know how the interface is implemented in the dll.

推荐答案

要在单元测试中使用接口的实现,应使用诸如

For using implementations of interfaces in a unit test, you should use a mocking framework like Moq and you can set up those interfaces to return the default values that satisfy your testing requirements. In this case, you would create a Mock to set up the values you would expect to see in this particular expected use case and then pass that into your controller.

var mockClientData = new Mock<IClientData>();

mockClientData.SetupGet(data => data.MyProperty).Returns(3);
// mockClientData.Object.MyProperty now returns 3

mockClientData.Setup(data => data.MyMethod()).Returns(42);
// mockClientData.Object.MyMethod() now returns 42
// any other setup that you need done goes here

var controller = new HomeController(mockClientData.Object);

// the rest of your test as normal

需要特别注意的是,您不应该在单元测试中依赖于依赖项的实现,因为那样您就不再在测试代码单元了,而是在编写集成测试.

It's important to note that you shouldn't rely on an implementation of a dependency in a unit test, because then you are no longer testing a unit of code - you are writing an integration test.

这篇关于使用结构图通过依赖注入进行单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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