简体   繁体   English

将单元测试附加到C#项目的标准方法

[英]Standard way to attach unit tests to a C# project

I've written couple of unit tests in seperate project. 我在单独的项目中编写了几个单元测试。 While developing, I loaded the dll into NUnit.exe each time to check the results. 在开发过程中,我每次都将dll加载到NUnit.exe中以检查结果。 Given that I am done with writing unit tests, how to organize and attach unit tests to the solution. 既然我完成了编写单元测试的工作,那么如何组织单元测试并将其附加到解决方案中。

I'd tried creating "tools" folder in the solution directory and then placed all NUnit related libraries and in postbuild event of the test project I hooked up the nunit like below and it works. 我曾尝试在解决方案目录中创建“ tools”文件夹,然后将所有与NUnit相关的库放入其中,在测试项目的postbuild事件中,我如下图所示连接了nunit,它可以正常工作。

"$(SolutionDir)tools\nunit\nunit-console.exe" "$(TargetPath)"

But in one of my tests, I refer to a sqlite DB. 但是在我的一项测试中,我指的是sqlite数据库。 If I hardcode its location it works fine but I intend to place it in the tests project under "App_Data" folder. 如果我对它的位置进行硬编码,则可以正常工作,但是我打算将其放在“ App_Data”文件夹下的测试项目中。 So, I tried with below code to get relative path but it is not working. 因此,我尝试使用下面的代码来获取相对路径,但是它不起作用。 But when I copied the file to "tools" folder it is working fine, I'd guess execution context is from NUnit folder. 但是,当我将文件复制到“ tools”文件夹时,它工作正常,我猜想执行上下文来自NUnit文件夹。

Path.Combine(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location),"App_Data\\test.txt")

If you don't need specifically nunit, you could as well use built-in visual studio support for unit testing... It has been incorporated to the newest Express editions as well and you don't have to struggle with problems like this ;) 如果您不需要特定的nunit,则可以使用内置的Visual Studio支持进行单元测试...它也已集成到最新的Express版本中,您不必为此类问题而苦恼; )

Either way, I believe you've misunderstood the basics of unit testing. 无论哪种方式,我相信您都误解了单元测试的基础知识。 We never test against an actual database, that's a very bad practice. 我们从不对实际的数据库进行测试,这是非常糟糕的做法。 You should do some research on the topic and see the theory behind mocking stuff like this. 你应该做的话题的一些研究,看看背后的理论mocking这样的东西。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM