Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unconstrained Isolation (mocking) framework for dotnet core

I'm working on a dotnet core project, trying to mock some third party classes in my Xunit.net tests. The class I'm trying to fake is not mockable through constrained frameworks like Moq or NSubstitute. So I need an unconstrained framework to do that.

Say I want to fake DateTime.Now in my .net core test projects.

In .net 4.5 we have MSFakes(Moles), Smocks, etc. None of them support dotnet core framework yet. Shim is not ported to dotnet core yet.

Anyone knows any isolation framework or technique that will achieve my goal for .NET Core at the present time?

like image 458
akardon Avatar asked Feb 23 '26 19:02

akardon


2 Answers

You could try a different way: wrap those third party libs with your own interfaces and wrapper classes. Then use a dummy object implementing that interface.

Things become more complicated with static properties like DateTime.Now. But it works similar: define an ITimeProvider interface with a Now property. Add a DateTimeWrapper : ITimeProvider with a public DateTime Now => DateTime.Now;, and - for convenience, but not required - a static class around it, e.g.

static class MyClock 
{ 
    static ITimeProvider _Instance; 
    static void SetInstanceForTesting(ITimeProvider instance) 
    { _Instance = instance; }
    static DateTime Now => _Instance.Now; 
}

Alternatively, you may inject an ITimeProvider instance to the objects needing it.

like image 181
Bernhard Hiller Avatar answered Feb 25 '26 15:02

Bernhard Hiller


A somewhat late reply, but for anyone else looking after the same kind of functionality I would recommend the open source git project prig: https://github.com/urasandesu/Prig It can fake static methods (they even have an example of faking and isolating DateTime.Now) and is an alternative to Microsoft Fakes, TypeMock and JustMock (all who cost money or require ultimate editions of visual studio to use).

like image 34
Anders Asplund Avatar answered Feb 25 '26 13:02

Anders Asplund