Skip to content

Issues With Mocking #1

@JasonBock

Description

@JasonBock

I'm trying to use this library, and I cannot mock static members, sealed types, or non-virtual members. According to the docs, it sounds like this should be possible, but with 1.0.0, I can't get these to work

For example, the docs state this should work:

var fixedDate = DateTime.UtcNow;

var staticMock = Mock.Static<DateTime>()
    .Returns(d => d.Now, fixedDate)
    .Build();

However, I get this compilation error when I try that:

The type 'DateTime' must be a reference type in order to use it as parameter 'T' in the generic type or method 'Mock.Static<T>()'

So then I tried to create my own type:

public sealed class MyDateTime
{
    public static DateTime UtcNow => DateTime.UtcNow;
}

But when I do this:

var staticMock = Mock.Static<MyDateTime>()
    .Returns(d => d.UtcNow, fixedDate)
    .Build();

This doesn't work either, because you can't reference UtcNow this way.

I tried a sealed type with a non-virtual member:

public sealed class Target
{
    public int MockThis(string value) => value.Length;
}

var staticMock = Mock.Static<Target>()
    .Returns(d => d.MockThis("value"), 1)
    .Build();

var mock = staticMock.Wrapped;
Console.WriteLine(mock.MockThis("value"));

Then I get a run-time error:

System.InvalidOperationException: Static types cannot be accessed directly. Use the wrapper methods instead.

OK, fine:

var staticMock = Mock.Of<Target>()
    .Setup(d => d.MockThis("value"), 1)
    .Build();

var mock = staticMock.Object;
Console.WriteLine(mock.MockThis("value"));

But this doesn't work either:

System.InvalidOperationException: Mock proxy for Target not found. Ensure NimbleMock.SourceGenerator is referenced and the type is mocked.

So, if it is possible to handle static members, sealed types, and non-virtual members, I can't get it to work. What am I missing?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions