Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unit testing a method that uses Assembly

I need to xUnit test a method that uses Assembly, specifically called with parameter Assembly.GetEntryAssembly().

But unfortunately in unit test project, the entry assembly appears to be testhost not my test project. 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?

like image 819
rethabile Avatar asked Apr 05 '17 22:04

rethabile


People also ask

Which method is used for unit testing?

Unit tests can be performed manually or automated. Those employing a manual method may have an instinctual document made detailing each step in the process; however, automated testing is the more common method to unit tests. Automated approaches commonly use a testing framework to develop test cases.

What does assembly testing mean?

a test requiring participants to put together elements in the creation of a whole. Usually assessing perceptual organization among other abilities. ASSEMBLY TEST: "A person took an assembly test in order to see how their perceptual organization abilities were working."

What are the two types of unit testing?

There are 2 types of Unit Testing: Manual, and Automated.

What is unit testing in unity?

A Unit Test is defined as a test that is focused on a “unit” of code. We should design a unit test to validate that a small, logical, snippet of code performs exactly as you expect it to in a specific scenario. With TDD, you write tests before you write your business logic.


1 Answers

Not all code should be tested. Extract the code where you use Assembly.GetEntryAssembly() into a separate component, something like this:

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. Then the code that you'd like to test should consume IAssemblyProvider, so you can substitute this with a stub:

// 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.

like image 69
trailmax Avatar answered Nov 06 '22 20:11

trailmax