如何在单元测试中模拟自定义类? [英] How to mock the custom class in unit testing?

查看:92
本文介绍了如何在单元测试中模拟自定义类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Xunit.net对应用程序服务进行单元测试。



由于以下声明,我的单元测试用例未得到部分执行:

StringCipher stringCipher = new StringCipher();



StringCipher是我编写密码加密和解密逻辑的类。



即使它进入StringCipher类的构造函数,但在构造函数中抛出异常:



I am doing the unit testing of application service using Xunit.net.

My unit test case is not getting partially executed because of following statement:
StringCipher stringCipher = new StringCipher();

StringCipher is class in which I have written the logic for password encryption and decryption.

Even it goes inside the constructor of StringCipher class but throwing exception inside the constructor:

public class StringCipher
{
private readonly byte[] _initVectorBytes = null;       
        private const int KeySize = 256;
        public StringCipher()
        {
            _initVectorBytes = Encoding.ASCII.GetBytes(ConfigurationManager.AppSettings["PasswordEncryptionKey"]);
        }
}







请让我知道如何解决这个问题问题?




Please let me know how can I resolve this issue?

推荐答案

我已将appsettings值复制到我的测试项目类。
I have copied appsettings values to my test project class.


只是复制的替代方法测试项目的应用程序如下:



在测试项目中右键单击,添加,现有项目。



导航到您要测试的项目的App.Config。

而不是单击添加,单击旁边的向下箭头并选择添加为链接 。



这意味着解决方案中的两个项目都指向完全相同的文件 - 这意味着您不必保持两个项目同步。



您可以看到解决方案资源管理器中的图标略有不同 - 在测试项目中,图标上有快捷方式标记。事实上,如果你单击Test项目中的App.config,它将跳转到另一个项目中的实际文件。



注意 - 如果你添加为链接bin文件夹中的文件,当您重建解决方案时,您可能会在测试项目中收到错误,说明该文件不存在 - 如果再次重建,这将会消失(因为第一个版本会将项目app.config复制到正确的文件夹) - 只要将始终复制设置为复制到输出目录选项。
An alternative to just copying the appsettings to the test project is as follows:

In your test project right-click, Add, Existing Item.

Navigate to the App.Config for the project you are trying to test.
Instead of just clicking "Add" click the down-arrow next to it and select "Add as Link".

This means that both projects in the solution are "pointing at" exactly the same file - which means you don't have to keep the two of them synchronised.

You can see that the icons in Solution Explorer are slightly different - in the test project there is "shortcut" marker on the icon. In fact if you click on App.config in the Test project it will "jump" to the actual file in the other project.

Note - if you Add As Link a file from the bin folder you may get an error in the test project when you rebuild the solution saying that the file does not exist - if you rebuild again this will go away (because the first build will have copied the project app.config to the correct folder) - as long as you have "Copy Always" set as the "Copy to Output Directory" option.


这篇关于如何在单元测试中模拟自定义类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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