How to unit test static methods in C# (2024)

.NET Programming

By Joydip Kanjilal, Contributor, InfoWorld |

Learn when static methods can’t be unit tested and how to use wrapper classes and the Moq and xUnit frameworks to unit test them when they can

When building or working in .NET applications you might often use static methods. Methods in C# can be either static or non-static. A non-static method (also known as an instance method) can be invoked on an instance of the class to which it belongs. Static methods don’t need an instance of the class to be invoked — they can be called on the class itself.

Although testing a non-static method (at least one that doesn’t call a static method or interact with external dependencies) is straightforward, testing a static method is not an easy task at all. This article talks about how you can overcome this challenge and test static methods in C#.

[ Also on InfoWorld: How to refactor God objects in C# ]

To work with the code examples provided in this article, you should have Visual Studio 2019 installed in your system. If you don’t already have a copy, you can download Visual Studio 2019 here.

Create a .NET Core console application project in Visual Studio

First off, let’s create a .NET Core Console Application project in Visual Studio. Assuming Visual Studio 2019 is installed in your system, follow the steps outlined below to create a new .NET Core console application project in Visual Studio.

  1. Launch the Visual Studio IDE.
  2. Click on “Create new project.”
  3. In the “Create new project” window, select “Console App (.NET Core)” from the list of templates displayed.
  4. Click Next.
  5. In the “Configure your new project” window shown next, specify the name and location for the new project.
  6. Click Create.

This will create a new .NET Core console application project in Visual Studio 2019. In similar fashion, create two more projects – a class library and a unit test (xUnit test) project. We’ll use these three projects to illustrate unit testing of static methods in the subsequent sections of this article.

When a static method can and can’t be unit tested

Unit testing a static method is no different than unit testing a non-static method. Static methods are not untestable in themselves. A static method that holds no state or doesn’t change state can be unit tested. As long as the method and its dependencies are idempotent, the method can be unit tested. The problems arise when the static method calls other methods or when the object being tested calls the static method. On the other hand, if the object being tested calls an instance method, then you can unit test it easily.

A static method cannot be unit tested if any of the following holds true:

  • The static method interacts with external dependencies such as a database, file system, network, or external API.
  • The static method holds state information, i.e., if it caches data into a static object of the class.

Consider the following code snippet that shows two classes, namely ProductBL and Logger. While ProductBL is a non-static class, Logger is a static class. Note that the Write method of the Logger class has been called from the LogMessage method of the ProductBL class.

public class ProductBL
{
public void LogMessage(string message)
{
Logger.Write(message);
}
}
public class Logger
{
public static void Write(string message)
{
//Write your code here to log data
}
}

Assume that the Write method of the Logger class connects to a database and then writes the data to a database table. The name of the database and its table where the data should be written might be pre-configured in the appsettings.json file. How can you now write unit tests for the ProductBL method?

Note that static methods cannot be mocked easily. As an example, if you have two classes named A and B and class A uses a static member of class B, you wouldn’t be able to unit test class A in isolation.

Three ways to unit test static methods

You can use Moq to mock non-static methods but it cannot be used to mock static methods. Although static methods cannot be mocked easily, there are a few ways to mock static methods.

You can take advantage of the Moles or Fakes framework from Microsoft to mock static method calls. (The Fakes framework was included in Visual Studio 2012 as the successor to Moles – it is the next generation of Moles and Stubs.) Another way to mock static method calls is by using delegates. There is yet another way to mock static method calls in an application – by using wrapper classes and dependency injection.

IMHO this last option is the best solution to the problem. All you need to do is wrap the static method call inside an instance method and then use dependency injection to inject an instance of the wrapper class to the class under test.

Create a wrapper class in C#

The following code snippet illustrates the LogWrapper class that implements the IWrapper interface and wraps a call to the Logger.Write() method inside an instance method called LogData.

public class LogWrapper : IWrapper
{
string _message = null;
public LogWrapper(string message)
{
_message = message;
}
public void LogData(string message)
{
_message = message;
Logger.Write(_message);
}
}

The following code snippet shows the IWrapper interface. It contains the declaration of the LogData method.

public interface IWrapper
{
void LogData(string message);
}

The ProductBL class uses dependency injection (constructor injection) to inject an instance of the LogWrapper class as shown in the code listing given below.

public class ProductBL
{
readonly IWrapper _wrapper;
static string _message = null;
public ProductBL(IWrapper wrapper)
{
_wrapper = wrapper;
}
public void LogMessage(string message)
{
_message = message;
_wrapper.LogData(_message);
}
}

The LogMessage method of the ProductBL class calls the LogData method on the instance of the LogWrapper class that has been injected earlier.

Use xUnit and Moq to create a unit test method in C#

Open the file UnitTest1.cs and rename the UnitTest1 class to UnitTestForStaticMethodsDemo. The UnitTest1.cs files would automatically be renamed to UnitTestForStaticMethodsDemo.cs. We’ll now take advantage of the Moq framework to set up, test, and verify mocks.

The following code snippet illustrates how you can use the Moq framework to unit test methods in C#.

var mock = new Mock<IWrapper>();
mock.Setup(x => x.LogData(It.IsAny<string>()));
new ProductBL(mock.Object).LogMessage("Hello World!");
mock.VerifyAll();

When you execute the test, here’s how the output should look in the Test Explorer Window.

How to unit test static methods in C# (3) IDG

The complete code listing of the test class is given below for your reference.

public class UnitTestForStaticMethodsDemo
{
[Fact]
public void StaticMethodTest()
{
var mock = new Mock<IWrapper>();
mock.Setup(x => x.LogData(It.IsAny<string>()));
new ProductBL(mock.Object).LogMessage("Hello World!");
mock.VerifyAll();
}
}

Unit testing is a process that tests units of code in an application to check if the actual results from your unit test match the desired results. If used judiciously unit testing can help prevent bugs in the development phase of a project.

Static methods can pose a number of problems when you attempt to unit test them using mocks. If your application requires you to mock a static method, you should consider that a design smell – i.e., an indicator of a bad design. I’ll discuss mocks, fakes, and stubs in more detail in a future article here.

How to do more in C#:

  • How to refactor God objects in C#
  • How to use ValueTask in C#
  • How to use immutability in C
  • How to use const, readonly, and static in C#
  • How to use data annotations in C#
  • How to work with GUIDs in C# 8
  • When to use an abstract class vs. interface in C#
  • How to work with AutoMapper in C#
  • How to use lambda expressions in C#
  • How to work with Action, Func, and Predicate delegates in C#
  • How to work with delegates in C#
  • How to implement a simple logger in C#
  • How to work with attributes in C#
  • How to work with log4net in C#
  • How to implement the repository design pattern in C#
  • How to work with reflection in C#
  • How to work with filesystemwatcher in C#
  • How to perform lazy initialization in C#
  • How to work with MSMQ in C#
  • How to work with extension methods in C#
  • How to us lambda expressions in C#
  • When to use the volatile keyword in C#
  • How to use the yield keyword in C#
  • How to implement polymorphism in C#
  • How to build your own task scheduler in C#
  • How to work with RabbitMQ in C#
  • How to work with a tuple in C#
  • Exploring virtual and abstract methods in C#
  • How to use the Dapper ORM in C#
  • How to use the flyweight design pattern in C#

Next read this:

  • Why companies are leaving the cloud
  • 5 easy ways to run an LLM locally
  • Coding with AI: Tips and best practices from developers
  • Meet Zig: The modern alternative to C
  • What is generative AI? Artificial intelligence that creates
  • The best open source software of 2023

Related:

  • C#
  • Microsoft .NET
  • Software Development

Joydip Kanjilal is a Microsoft MVP in ASP.NET, as well as a speaker and author of several books and articles. He has more than 20 years of experience in IT including more than 16 years in Microsoft .NET and related technologies.

Follow

Copyright © 2020 IDG Communications, Inc.

How to unit test static methods in C# (2024)

FAQs

How to unit test static methods in C#? ›

All you need to do is wrap the static method call inside an instance method and then use dependency injection to inject an instance of the wrapper class to the class under test.

How to unit test static function in C? ›

Solution
  1. Step 0: write the test. Let's write the test cases first, our test-example.c file looks like this: ...
  2. Step 1: include the real source file. ...
  3. Step 2: move main out of the way. ...
  4. Step 3: mock the missing pieces. ...
  5. Step 4: hook up the compiler and linker.

How to test private static method in C#? ›

Unit Testing a private static method in C# . NET
  1. public class Maths.
  2. private static int CalculatePower(int Base, int Exponent)
  3. int Product = 1;
  4. for (int i = 1; i <= Exponent; i++) {
  5. return Product;
  6. [TestMethod()]
  7. public void CalculatePowerTest()
  8. PrivateType privateTypeObject = new PrivateType(typeof(Maths));

How to test static methods in JUnit? ›

Here's an example of how to use PowerMock with JUnit to test a static method:
  1. javaCopy code@RunWith(PowerMockRunner.class)
  2. @PrepareForTest(MyClass.class) // Specify the class with the static method to be tested.
  3. public class MyClassTest {
  4. @Test.
  5. public void testStaticMethod() {
  6. // Mock the static method.
Sep 26, 2023

How to write unit test cases for methods in C#? ›

We can write a unit test in seven easy steps.
  1. Choose a Framework to Use When Writing Tests.
  2. Create a Separate Project for Your Tests.
  3. Identify the Components in a Solution.
  4. Create an Empty Test.
  5. Fill in the Test Steps.
  6. Write the Code.
  7. Run the Test.
May 24, 2023

Can you unit test static functions? ›

Static functions that are fast, do not have a complex set up and have no side effects such as your example are therefore fine to use directly in unit tests. If you have code that is slow, complex to set up or has side effects, then mocks are useful.

How do you test for static? ›

Rub a glass rod with silk or cotton, or pull a plastic comb through your hair: The glass and the comb will collect extra electrons and become negatively charged, while the fabric pieces and the hair will lose electrons and become positively charged.

Can we test static class in C#? ›

Testing private static methods in C# can be a tricky task as they are not directly accessible from outside the class. However, it is still possible to test these methods using various techniques.

Can we test private methods in unit testing C#? ›

Private methods are part of the details/internals about the class—the innards. Unit testing should be testing the unit that's accessible rather than the internals. In other words, it should only be concerned with testing the interface to the class—that is, the public methods.

Can we write unit test for private methods? ›

The answer is no. It's important to understand that our private method doesn't exist in a vacuum. It'll only be called after the data is validated in our public method.

Why is it hard to test static methods? ›

This is because static methods are associated with a class, rather than an instance of that class, and mocking frameworks typically work with instances of classes.

How to mock a static method call inside another method? ›

0, we can use the Mockito. mockStatic(Class<T> classToMock) method to mock invocations to static method calls. This method returns a MockedStatic object for our type, which is a scoped mock object. Therefore, in our unit test above, the utilities variable represents a mock with a thread-local explicit scope.

Can you test static classes? ›

Because static classes cannot be mocked, it is very difficult to test components that use them. Furthermore, some static classes may have external side effects or dependencies, for example File. ReadAllText requires an actual physical file to reside at the specified location or the call will fail.

What is Assert in C# unit test? ›

The Assert section verifies that the action of the method under test behaves as expected. For . NET, methods in the Assert class are often used for verification.

How to run a single unit test in C#? ›

Select the individual tests that you want to run, open the right-click menu for a selected test and then choose Run Selected Tests (or press Ctrl + R, T). If individual tests have no dependencies that prevent them from being run in any order, turn on parallel test execution in the settings menu of the toolbar.

What is mock in unit testing C#? ›

This helps to ensure that the code works correctly and that any changes to the code do not break existing functionality. This is where mocking comes in. Mocking is a technique that allows us to create fake objects that simulate the behavior of real objects.

How to test static variable in C? ›

Syntax of Static Variable in C

The syntax for declaring a static variable in C programming language is as follows: static data_type variable_name; In this syntax, "data_type" refers to the data type of the variable being declared (e.g., int, float, double, etc.), and "variable_name" is the name given to the variable.

How do you test a function in a unit test? ›

A typical unit test contains 3 phases: First, it initializes a small piece of an application it wants to test (also known as the system under test, or SUT), then it applies some stimulus to the system under test (usually by calling a method on it), and finally, it observes the resulting behavior.

How to declare static variable in function C? ›

Whenever you call the function, the static variable value will be increased by 1.
  1. Explore free C programming courses. ...
  2. Syntax to declare a static variable: static data_type variable_name; ...
  3. Syntax of Static variable: static data_type variable_name = initial_value;
  4. For example: static int variable = 24;
Mar 16, 2023

Top Articles
Latest Posts
Article information

Author: Merrill Bechtelar CPA

Last Updated:

Views: 6424

Rating: 5 / 5 (50 voted)

Reviews: 89% of readers found this page helpful

Author information

Name: Merrill Bechtelar CPA

Birthday: 1996-05-19

Address: Apt. 114 873 White Lodge, Libbyfurt, CA 93006

Phone: +5983010455207

Job: Legacy Representative

Hobby: Blacksmithing, Urban exploration, Sudoku, Slacklining, Creative writing, Community, Letterboxing

Introduction: My name is Merrill Bechtelar CPA, I am a clean, agreeable, glorious, magnificent, witty, enchanting, comfortable person who loves writing and wants to share my knowledge and understanding with you.