How to unit test methods dependent on static methods in C#? - c#

A method in the service which I'm unit testing is calling a static method that is present in another service.
I'm new to unit testing and have no idea how to mock these kinda dependencies. Please suggest!

There is already a thread here about this topic.
In fact it is not possible to create a service facade (Mock) for static methods.
My suggestion here is to refactor your code in that way that you make your class non static and create an interface for it. Than you can inject your dependency class in the normal system via IOC and in the unit test you can create a mock with frameworks like Moq or Rhinomocks.

Related

Unit test a singleton class with MSTest

I want to test my class EventTextsDB that is a singleton, using MSTest in .NET 6.
I first thought about using AppDomain, but they basically were removed in .NET 5+ (https://learn.microsoft.com/en-us/dotnet/core/porting/net-framework-tech-unavailable#application-domains)
Then I found Unit test singletons, but by calling the private constructor via reflection I still cannot test the static Create() and static Delete() methods in the class, because they set the static EventTextsDB Instance property.
I could use ordered unit tests, but this would require a lot of work because I would have to order all tests that used this class. Not many tests use or test this class yet, but many do with a similar class LanguageDB, at which I want to apply the same solution that I am looking for.
I have read somewhere on stackoverflow or MSDN, that each test assembly runs isolated (in different AppDomain, if they still exist?), but I don't want to create 10 new test assemblies just for 10 tests of this class.
How can I test my singleton class?

How to mock away Process.GetProcessesByName() call in a method I want to test?

I am writing a unit tests using Xunit and moq. Within one function it calls Process.GetProcessesByName(). I need this to return a process with a certain pid which would exist when my program is actually running. However since in the test this process won't exist how do I mock away this call to return a fake process I want so I can continue to test the rest of the method?
You will need to wrap the call to Process.GetProcessesByName() in an injectable class in order to mock it. There is no way for Moq to replace behaviour of static methods.
There's a good answer on this topic here: How to mock static methods in c# using MOQ framework?
What you might be trying is a system testing/Integration testing. Trying to get actual value during unit testing is not what Unit testing is meant to do. The scope of unit testing is to validate the functionality of the piece of code not on the data. If you are interested in testing the actual data, try other testing methods like automation testing.

Skipping private methods during unit test C#

public bool A (UserRequest foo)
{
ClientRequest boo = B(foo); //Mapping local model to client model
C(boo);
return result;
}
I want to write an unit test for method A to test method B but I don't want my unit test to call method C. Method C is a private method but it makes calls to a third party client. I am unable to setup method C in my Unit Test since the type "ClientRequest" doesn't have a reference in the test case assembly. How can this be implemented without adding a reference of the client dll to my test assembly as well. How to skip calling method C ?
C is a private method
Things are private for a reason. They are implementation details to which consuming code shouldn't be coupled. And unit tests are consuming code.
it makes calls to a third party client
Therein lies the problem with your unit tests. Don't try to break apart the class being tested, digging into its internals and ultimately modifying what it's doing and as a result invalidating the tests in the first place.
Instead, isolate and mock the dependency. Somewhere in C() this class has an external dependency. Instead of obscuring that dependency deep within the class, wrap it in an interface/implementation and provide that implementation to the class. (This is called Dependency Injection. There are frameworks which provide rich functionality around the concept, but the concept itself can be achieved manually for simple cases as well.)
So when application code uses this class, instances are provided with an implementation of the dependency which calls the external service. And when unit tests use this class, instances are provided with a mock implementation that pretends to call the external service.
Then your tests can include mocking the results of that service as well, triggering controlled failure responses to test how the class handles them.

how to create mock of static class using Rhino

I am using Rhino.Mocks to mock objects for unit testing my .net application. I want to mock a static class. If someone has idea of how to do this, please suggest.
Short answer : you can't.
You can wrap the static up in a facade object and then mock that which will probably acheive wwhat you want.
See Mocking Static methods using Rhino.Mocks

What should be the strategy of unit testing when using IoC?

After all what I have read about Dependency Injection and IoC I have decided to try to use Windsor Container within our application (it's a 50K LOC multi-layer web app, so I hope it's not an overkill there). I have used a simple static class for wrapping the container and I initialize it when starting the app, which works quite fine for now.
My question is about unit testing. I know that DI is going to make my life much easier there by giving me the possibility of injecting stub / mock implementations of class collaborators to the class under test. I have already written a couple of tests using this technique and it seems to make sense for me. What I am not sure about is whether I should be using IoC (in this case Windsor Castle) also in unit tests (probably somehow configure it to return stubs / mocks for my special cases) or is it better to wire-up all the dependencies manually in the tests. What do you think and what practice has worked for you ?
You don't need DI container in unit tests because dependencies are provided through mock objects generated with frameworks such as Rhino Mocks or Moq. So for example when you are testing a class that has a dependency on some interface this dependency is usually provided through constructor injection.
public class SomeClassToTest
{
private readonly ISomeDependentObject _dep;
public SomeClassToTest(ISomeDependentObject dep)
{
_dep = dep;
}
public int SomeMethodToTest()
{
return _dep.Method1() + _dep.Method2();
}
}
In your application you will use a DI framework to pass some real implementation of ISomeDependentObject in the constructor which could itself have dependencies on other objects while in a unit test you create a mock object because you only want to test this class in isolation. Example with Rhino Mocks:
[TestMethod]
public void SomeClassToTest_SomeMethodToTest()
{
// arrange
var depStub = MockRepository.CreateStub<ISomeDependentObject>();
var sut = new SomeClassToTest(depStub);
depStub.Stub(x => x.Method1()).Return(1);
depStub.Stub(x => x.Method2()).Return(2);
// act
var actual = sut.SomeMethodToTest();
// assert
Assert.AreEqual(3, actual);
}
I'm working on an ASP.NET MVC project with about 400 unit tests. I am using Ninject for dependency injection and MBUnit for testing.
Ninject is not really necessary for unit testing, but it reduces the amount of code I have to type. I only have to specify once (per project) how my interfaces should be instantiated as opposed to doing this every time I initialize the class being tested.
In order to save time on writing new tests, I have created test fixture base classes with as much generic setup code as possible. The setup procedures in those classes intialize fake repositories, create some test data and a fake identity for the test user. Unit tests only initialize data that is too specific to go into generic setup procedures.
I am also mocking objects (as opposed to faking) in some tests, but I found that faking data repositories results in less work and more accurate tests.
For example, it would be more difficult to check if the method under test I properly commits all updates to the repository after making them when using a repository mock than when I am using a repository fake.
It was quite a bit of work to set up at the beginning, but really helped me reduce save a lot of time in the long run.
I've just written a very similar style and size app. I wouldn't put any dependency injection in the unit tests because it is not complicated enough to be necessary. You should use a mocking framework to create your mocks (RhinoMocks / Moq).
Also Automocking in Moq or the Auto Mock Container in Rhinomocks will simplify building your mocks further.
Auto mocking allows you to get object
of the type you want to test without
setting up mocks by hand. All
dependencies are mocked automatically
(assuming they are interfaces) and
injected into the type constructor. If
you need to you can set up expected
behavior, but you don't have to.
As Darin has already pointed out, you don't need to use DI if you have mocks. (However, DI has a few other benefits as well, including, first of all, lessening dependencies in your code, which makes your code much easier to maintain and extend in the long run.)
I personally prefer wiring up everything in my unit tests, thus relying as little as possible on external frameworks, config files etc.

Categories

Resources