简体   繁体   English

单元测试使用Assembly的方法

[英]unit testing a method that uses Assembly

I need to xUnit test a method that uses Assembly , specifically called with parameter Assembly.GetEntryAssembly() . 我需要xUnit测试一个使用Assembly的方法,特别是用参数Assembly.GetEntryAssembly()调用。

But unfortunately in unit test project, the entry assembly appears to be testhost not my test project. 但不幸的是,在单元测试项目中,入口程序集似乎是testhost而不是我的测试项目。 That way I'll not be able to search my test project. 这样我就无法搜索我的测试项目。 Does that mean I won't be able to test this method? 这是否意味着我将无法测试此方法? or is the another way to go? 还是另一种方式?

Not all code should be tested. 并非所有代码都应该进行测试。 Extract the code where you use Assembly.GetEntryAssembly() into a separate component, something like this: 将使用Assembly.GetEntryAssembly()的代码解压缩到一个单独的组件中,如下所示:

public interface IAssemblyProvider
{
      Assembly GetEntryAssembly();
}

public class AssemlbyProvider : IAssemblyProvider
{
      public Assembly GetEntryAssembly()
      {
           return Assembly.GetEntryAssembly();
      }
}

And use this abstraction in your code. 并在代码中使用此抽象。 No need to test this single method - we know it works, this is part of .Net framework. 无需测试这种方法 - 我们知道它有效,这是.Net框架的一部分。 Then the code that you'd like to test should consume IAssemblyProvider , so you can substitute this with a stub: 那么您要测试的代码应该使用IAssemblyProvider ,因此您可以使用存根替换它:

// should only be visible in test project
internal class StubAssemlbyProvider : IAssemblyProvider
{
      public Assembly GetEntryAssembly()
      {
           return typeof(MyClassInEntryAssembly).Assembly;
      }
}

This way your code is tested, but you are not testing .Net framework code. 这样您的代码就会被测试,但您不会测试.Net框架代码。

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

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