CorryM
CorryM

Reputation: 135

Avoid calling a non-virtual method in a unit test

I'm tasked with writing some tests to one of our codebases. Now I have this class:

```

public class A 
{
  public void method_1() 
  { 
    this.method_2();
    // Do something
  }

  public void method_2() 
  {
     Environment.CurrentDirectory = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
     // Do something
  }
}

```

Now I'm trying to write a test for method_1 without invoking method_2 and getting NullReferenceException.

[TestClass]
public class MyTestClass
{

  [TestMethod]
  public void MyTestMethod()
  {
    // Ignore the call: Assembly.GetEntryAssembly() because it returns null>

    new A().method_1();
  } 

Any suggestion?

EDIT: I'm not allowed to change the code.

Upvotes: 0

Views: 378

Answers (2)

Carra
Carra

Reputation: 17964

Assuming you cannot change anything to the code, you can use MS Fakes to mock out static methods like DateTime.Now. Should also work on Assembly.GetEntryAssembly().


I'm not a big fan of MS Fakes though, had a few too many problems with it in the past. If you can make a small change to the code, you can make the method_2 virtual and do something like this:

public class MyTestA : A 
{
  public override void method_2() 
  {
    //Do nothing
  }
}

You can then write your tests against MyTestA.

Of course, putting the code in method 2 in a new class/interface and mock that as a dummy interface is an even cleaner solution.

Upvotes: 1

Christoph Fink
Christoph Fink

Reputation: 23113

Without the possibility to override/mock the logic inside method_2 there is not much you can do.
If it is your own codebase I suggest to move the call to Assembly.GetEntryAssembly().Location to some helper method which you can override for the tests.

Upvotes: 2

Related Questions