首页 \ 问答 \ Xml文件不复制到测试输出目录(Xml file not copying to test output directory)

Xml文件不复制到测试输出目录(Xml file not copying to test output directory)

Visual Studio 2010,x64机器,使用内置的Web服务器通过内置测试框架的一组单元测试来托管WCF服务。

我有一个XML文件,我的测试需要加载才能运行。 我已将该文件包含在测试项目中,并将文件设置为“内容”,并始终复制到输出目录。 这个文件拷贝到bin \ debug目录下。

然而,当我执行测试时,xml文件不在那里。 而不是查看项目的bin \ debug文件夹,它会在测试的工作目录C:\ Projects \ SAP Reapprovals \ TestResults \ name_machine 2010-12-06 13_45_43 \ Out“中查找该文件,该文件未被复制到。

有没有办法强制这个文件复制,还是需要从测试中完全符合参考资格?

TIA!
詹姆士


更新
我设置了DeploymentItem属性,但文件仍然不会复制。 但那肯定看起来像我想要的...任何想法为什么不起作用?

我的测试代码:

[TestMethod]
[DeploymentItem("SAP - GS3 format.xml")]
public void TestProcessSapRoles() {

    //  I get a 'file not found' error here, and when 
    //  I check the output directory, it isn't there
    XElement rolesRoot = XElement.Load("SAP - GS3 format.xml");

}


解答:
感谢出门到CPedros,他的帮助我放大了一点。 我运行了SysInternals的进程监视器,看看它在寻找我的xml文件。 这是我发现的:

当我使用ctrl + r,ctrl + t(当前上下文中的调试测试)运行测试时, visual studio 完全 忽略 DeploymentItem 属性 ,甚至没有尝试将文件复制到任何位置。 在这种情况下,当我尝试打开它进行阅读时,我收到一个“找不到文件”异常。 Visual Studio为测试创建了一个临时工作目录,但其中只有一个文件,AgentRestart.dat。

当我使用工具栏中的“运行单元测试”按钮运行测试(不知道是什么测试选项)时,Visual Studio没有复制文件,而是直接从项目目录中引用它。 测试通过,没有创建临时工作目录。

当我从菜单选项“运行 - >当前上下文中的测试”运行测试(运行,而不是调试)时,创建了临时工作目录,并将xml文件和所有可执行文件复制到该目录。 测试通过了。

当我编辑Local.testsettings(在我的测试文件夹下的解决方案项目文件夹下)时,我从左侧菜单中选择了“部署”,并添加了xml文件。 它被添加为[解决方案目录] \ [项目目录] \ file.xml。 我删除了DeploymentItem属性。 现在我可以调试测试了 将xml文件和所有可执行文件复制到为测试创建的临时目录。

TLDR: Visual Studio忽略了DeploymentItem属性,以确定某些运行测试的方式。 解决方案是编辑Local.testsettingsDeployment菜单,并手动添加文件。

谢谢您的帮助! 我给出了CPedros的答复,因为它是最有帮助的解决这个问题。


Visual Studio 2010, x64 machine, using the built-in web server to host a WCF service with a set of unit tests using the built-in test framework.

I have an XML file that my tests need to load to run. I've included this file in the test project, and have the file set to 'content' and 'always copy to output directory'. This file copies to the bin\debug directory fine.

When I execute the tests, however, the xml file is not there. Instead of looking in the project's bin\debug folder, it looks for it in the test's working directory, C:\Projects\SAP Reapprovals\TestResults\name_machine 2010-12-06 13_45_43\Out". The file hasn't been copied there.

Is there a way to force this file to copy, or do I need to fully qualify the reference from within the test?

TIA!
James


Update
I set the DeploymentItem attribute, but the file still doesn't copy. But that sure looks like what I want... any ideas why that isn't working?

My test code:

[TestMethod]
[DeploymentItem("SAP - GS3 format.xml")]
public void TestProcessSapRoles() {

    //  I get a 'file not found' error here, and when 
    //  I check the output directory, it isn't there
    XElement rolesRoot = XElement.Load("SAP - GS3 format.xml");

}


ANSWERS:
Thanks go out to CPedros, with his help I've zoomed in on this a bit. I ran SysInternals' Process Monitor, to see where it was looking for my xml file. Here's what I found:

When I ran the tests using ctrl+r,ctrl+t (debug tests in current context), visual studio ignored the DeploymentItem attribute completely and did not even try to copy the file anywhere. In this case I got a "File Not Found" exception when I tried to open it for reading. Visual studio created a temporary working directory for the tests, but there was only one file in it, AgentRestart.dat.

When I ran the tests using the 'Run Unit Tests' button in my toolbar (not sure what test option that is), Visual Studio did not copy the file over, but referenced it directly from the project directory. The test passed, and no temporary working directory was created.

When I ran the test from the menu option "run -> tests in current context" (run, not debug), a temporary working directory was created, and the xml file and all executables were copied to it. The test passed.

When I edited Local.testsettings (under a Solution Items folder under my tests folder), I chose 'Deployment' from the left menu, and added the xml file. It was added as [solution directory]\[project directory]\file.xml. I removed the DeploymentItem attribute. Now I was able to debug the tests; the xml file and all executables were copied to the temporary directory created for the test.

TLDR: Visual Studio is ignoring the DeploymentItem attribute for certain ways of running the test. The solution is to edit Local.testsettings, the Deployment menu, and add the file by hand.

Thanks for the help! I'm giving CPedros credit for his answer, as it was the most helpful in resolving this.


原文:https://stackoverflow.com/questions/4369861
更新时间:2024-04-04 06:04

最满意答案

getData()函数返回String值而不是可选值。 那么您应该使用?将getData函数的返回类型更改为可选值类型? 操作者

虽然你总是期望一个可选值,如果你的getData函数总是返回一个字符串值,那么使用while是没有意义的,因为你故意告诉编译器getData函数将总是返回一个String值并尝试解包它,所以我们不应该' t展开非可选值。

错误处理代码 (记住书面保持更快 ):

private func nextLine() throws -> String?{
     var returnData : String? = ""

     if arc4random_uniform(7) != 3 {
     returnData = "Genreated Random number other than 3"
     }else{
         throw NSError(domain: "Generated random number 3", code: 111, userInfo: nil)
      }
     return returnData
}

do {
     while let headerLine =  try nextLine() {
     //do something with the header
     print(headerLine)
     }
 }catch{

       //Handle exception
       print(error)
 }

如果生成的数字不等于3,则nextLine函数返回一个告诉“生成的3以外的随机数”的字符串,否则它将抛出一个可以在catch块中处理的异常。这里我有可能使nextLine函数返回一个可选的如果我删除? 从returnLine函数的返回类型。 它会给你一个错误,告诉“条件值的初始化器必须有可选类型而不是字符串”,这意味着编译器试图解包一个没有意义的非可选值。

考虑:

  var someIntegerValue = 5

  if let x = someIntegerValue
  {
    // it will give an error
  }

上面的代码会给你一个错误,告诉“条件绑定的Intializer必须有Optional类型,而不是Int”,因为即使在这里我们也试图解包非可选值。

 If you replace var some = 5 with var some : Int? = 5 it will be all right.

错误/异常处理:

你可以在获取应该在int块中写入的值之前使用try关键字,它将获取值或者它将触发异常,异常应该在catch块内处理。


Your getData( ) function returns a String value not an optional value. So you should change return type of getData function to optional value type using ? operator

while let always expects an optional value, if your getData function always returns a string value then using while let makes no sense because you are telling the compiler intentionally that getData function will always return a String value and trying to unwrap it, so we shouldn't unwrap a nonoptional value.

Code for error handling ( Written Keeping Swifter in mind ) :

private func nextLine() throws -> String?{
     var returnData : String? = ""

     if arc4random_uniform(7) != 3 {
     returnData = "Genreated Random number other than 3"
     }else{
         throw NSError(domain: "Generated random number 3", code: 111, userInfo: nil)
      }
     return returnData
}

do {
     while let headerLine =  try nextLine() {
     //do something with the header
     print(headerLine)
     }
 }catch{

       //Handle exception
       print(error)
 }

nextLine function returns a string telling "Generated Random number other than 3" if generated number is not equal to 3,or else it will throw an exception which can be handled in the catch block.Here I have potentially made nextLine function to return an optional value.If I remove ? from return type of nextLine function. It will give you an error telling "Initializer for conditional value must have optional type not String", it means compiler is trying to unwrap a non optional value which makes no sense.

Consider :

  var someIntegerValue = 5

  if let x = someIntegerValue
  {
    // it will give an error
  }

Above code will give you an error telling "Intializer for conditional binding must have Optional type,not Int",because even here we are trying to unwrap a non optional value.

 If you replace var some = 5 with var some : Int? = 5 it will be all right.

Error/Exception Handling :

you can make use of try keyword before fetching the value which should be inturn written inside do block ,it will either fetch value or it will fire an exception,exception should be handled inside catch block.

相关问答

更多
  • getData()函数返回String值而不是可选值。 那么您应该使用?将getData函数的返回类型更改为可选值类型? 操作者 虽然你总是期望一个可选值,如果你的getData函数总是返回一个字符串值,那么使用while是没有意义的,因为你故意告诉编译器getData函数将总是返回一个String值并尝试解包它,所以我们不应该' t展开非可选值。 错误处理代码 (记住书面保持更快 ): private func nextLine() throws -> String?{ var returnDa ...
  • Swift 2&3 事情在Swift 2中发生了一些变化,因为有一个新的错误处理机制,这与稍微更加类似于例外但不同的细节。 指示错误的可能性 如果函数/方法想要表明它可能会引发错误,它应该包含这样的throws关键字 func summonDefaultDragon() throws -> Dragon 注意:功能实际上可以抛出的错误类型没有规定。 该声明只是声明该函数可以抛出任何实现ErrorType的实例,或者根本不抛出。 2.调用可能会导致错误的功能 为了调用函数,你需要使用try关键字,像这样 t ...
  • 作为一般规则,请尽量避免使用强制解包(!) if let _: String= try! data.substring... 而是使用 if let index = data.index(of: "var sources2"), let _: String = try? data.substring(from: index) { ... } else { ... } 这样你就可以移除可能导致崩溃的两次强行拆卸。 您已经拥有if let保护以捕获nil值,因此您可以通过使用条件展开来充分利用它。 ...
  • 与错误状态一样,您需要添加没有约束的最终catch 。 Like the error states, you need to add a final catch without constraints.
  • 这是正确的实现, do { let jsonDictionary = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary //Use your dictionary here. print("JSON : \(jsonDictionary)") } catch { print(error) ...
  • 尝试一下 UIImagePNGRepresentation(img)?.writeToFile(imagePath, atomically: true) 代替。 查看Apple文档 。 编辑: 要更准确地回答您的问题,请使用Swift 2中的错误处理 。 do { try UIImagePNGRepresentation(img)?.writeToFile(imagePath, options: .DataWritingAtomic) } catch let error as NSError { ...
  • 更换 ! 在参数中? (因为那是方法的签名)示例: search.startWithCompletionHandler { (localResponse:MKLocalSearchResponse?, error:NSError?) -> Void in } Replace the ! in the arguments with ? (because that's the signature of the method) Example: search.startWithComp ...
  • AVCaptureDeviceInput有一个名为init(device:)初始化init(device:) ,然后如果无法初始化则throws outError 。 所以你可以try! AVCaptureDeviceInput(device: someDevice) try! AVCaptureDeviceInput(device: someDevice)意味着你“承诺”它不会失败(如果它会崩溃)。 或者你可以尝试/捕捉 do { try AVCaptureDeviceInput(device: ...
  • 你不需要var error: NSError? 再也没有 ,删除它和相关的行。 现在,您可以处理catch块中可能出现的错误。 func queueTrack() { let url = NSURL.fileURLWithPath(tracks[currentTrackIndex] as String) do { player = try AVAudioPlayer(contentsOfURL: url) player?.delegate = self ...
  • 这是代码: class ViewController: UIViewController { func saveText(text: String, path: String) -> Bool { do { try text.writeToFile(path, atomically: true, encoding: NSUTF8StringEncoding) return true } catch { print("Error saving ...

相关文章

更多

最新问答

更多
  • 您如何使用git diff文件,并将其应用于同一存储库的副本的本地分支?(How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?)
  • 将长浮点值剪切为2个小数点并复制到字符数组(Cut Long Float Value to 2 decimal points and copy to Character Array)
  • OctoberCMS侧边栏不呈现(OctoberCMS Sidebar not rendering)
  • 页面加载后对象是否有资格进行垃圾回收?(Are objects eligible for garbage collection after the page loads?)
  • codeigniter中的语言不能按预期工作(language in codeigniter doesn' t work as expected)
  • 在计算机拍照在哪里进入
  • 使用cin.get()从c ++中的输入流中丢弃不需要的字符(Using cin.get() to discard unwanted characters from the input stream in c++)
  • No for循环将在for循环中运行。(No for loop will run inside for loop. Testing for primes)
  • 单页应用程序:页面重新加载(Single Page Application: page reload)
  • 在循环中选择具有相似模式的列名称(Selecting Column Name With Similar Pattern in a Loop)
  • System.StackOverflow错误(System.StackOverflow error)
  • KnockoutJS未在嵌套模板上应用beforeRemove和afterAdd(KnockoutJS not applying beforeRemove and afterAdd on nested templates)
  • 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
  • android - 如何避免使用Samsung RFS文件系统延迟/冻结?(android - how to avoid lag/freezes with Samsung RFS filesystem?)
  • TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
  • 企业安全培训的各项内容
  • 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
  • C#类名中允许哪些字符?(What characters are allowed in C# class name?)
  • NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
  • 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
  • 将多个行和可变行移动到列(moving multiple and variable rows to columns)
  • 提交表单时忽略基础href,而不使用Javascript(ignore base href when submitting form, without using Javascript)
  • 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
  • Angular $资源不会改变方法(Angular $resource doesn't change method)
  • 在Angular 5中不是一个函数(is not a function in Angular 5)
  • 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
  • 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
  • 常见的python rpc和cli接口(Common python rpc and cli interface)
  • Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
  • 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)