如何在 Visual Studio 中从 Xunit 测试中引用测试文件? [英] How to refer to test files from Xunit tests in Visual Studio?

查看:16
本文介绍了如何在 Visual Studio 中从 Xunit 测试中引用测试文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们使用 Xunit 进行测试.我们使用 Xunit 插件通过内置的 Visual Studio 2013 Test Runner 运行我们的测试.

We’re using Xunit for testing. We’re running our tests via the built-in Visual Studio 2013 Test Runner, using the Xunit plugin.

问题是一些测试需要引用文件系统上的文件.似乎 Xunit(或 VS 测试运行器——不确定是哪个)在执行测试之前将汇编文件复制到另一个目录,但没有复制 bin 目录中的任何支持文件,因此找不到我们的测试文件.[MS 测试框架指定要复制的列表文件的属性,但 Xunit 没有.]

The issue is that some of the tests need to refer to files on the filesystem. It seems that Xunit (or the VS Test Runner—not sure which), copies the assembles, but not any supporting files in the bin directory, to another directory before executing the tests, hence our test files are not found. [The MS Testing framework specifies attributes for listing files to be copied, but Xunit does not.]

如何要么禁用这种复制行为,或者以编程方式确定原始 bin/ 目录位置以获取文件?

How to either disable this copying behaviour, or else programmatically determine the original bin/ directory location to fetch the files?

似乎大多数提议的解决方案(包括在 Xunit 错误跟踪器站点上)建议将文件存储为嵌入式资源,而不是始终复制"文件.但是,这并不总是实用的,例如:测试文件操作代码,以及(在一种情况下)需要 Sqlite 数据库文件的代码.

It seems that most proposed solutions (including on the Xunit bug-tracker site) suggest storing the files as embedded resources instead of ‘copy always’ files. However, this is not always practical, for example: testing file manipulation code, and (in one case) code which wants a Sqlite database file.

推荐答案

好吧,典型的,我一发布问题,我自己就找到了答案……

Okay, typical, just as soon as I post the question, I find the answer myself…

要点是程序集的复制(Shadow Copying)似乎是由 .NET 框架完成的,而不是由 Visual Studio 或 Xunit 完成的.

The gist is that the copying (Shadow Copying) of assemblies seems to be done by the .NET framework, not by Visual Studio or by Xunit.

我们一直在使用 Assembly.Location 来定位程序集文件,从而定位测试文件.然而,这是错误的,因为它为我们提供了 Shadow-Copied 组合而不是原件的位置.

We had been using Assembly.Location to locate the assembly file, and hence the test files. However, this was wrong, since it gave us the location of the Shadow-Copied assembles instead of the originals.

相反,您应该使用 Assembly.CodeBase 来获取基本汇编代码位置.但是,这是一个(文件)URL,因此需要从 URL 中提取路径.新的 (C#) 代码如下所示:

Instead you should use Assembly.CodeBase to fetch the base assembly code location. However, this is a (File) URL, so it’s necessary to extract the path from the URL. The new (C#) code looks like this:

var codeBaseUrl = new Uri(Assembly.GetExecutingAssembly().CodeBase);
var codeBasePath = Uri.UnescapeDataString(codeBaseUrl.AbsolutePath);
var dirPath = Path.GetDirectoryName(codeBasePath);
return Path.Combine(dirPath, relativePath);

...其中 relativePath 是相对于 Bin\ 目录的路径.

…where relativePath is the path relative to the Bin\ directory.

这篇关于如何在 Visual Studio 中从 Xunit 测试中引用测试文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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