daveoftheparty / speedy-moq

Generate boilerplate code for Moq in C#
MIT License
1 stars 0 forks source link

Speedy Moq

Code generation to speed up testing in C# using the excellent Moq library.

Demo GIF blurry? Scroll down for a text based demo.

Demo

Given:

namespace Demo.Lib
{
    public interface IStringAnalyzer
    {
        int CharOccurs(string text, char charToCount);
    }
}

And:

using NUnit.Framework; // or Xunit, Microsoft.VisualStudio.TestTools

namespace Demo.Lib.UnitTests
{
    public class StringAnalyzerTests
    {
        [Test]
        public void Go()
        {
            IStringAnalyzer
        }
    }
}

When: User clicks the lightbulb and chooses Generate Moq Setups

Then:

using System;
using System.Linq.Expressions;
using Moq;
using NUnit.Framework;

namespace Demo.Lib.UnitTests
{
    public class StringAnalyzerTests
    {
        [Test]
        public void Go()
        {
            var stringAnalyzer = new Mock<IStringAnalyzer>();
            Expression<Func<IStringAnalyzer, int>> charOccurs = x =>
                x.CharOccurs(It.IsAny<string>(), It.IsAny<char>());

            stringAnalyzer
                .Setup(charOccurs)
                .Returns((string text, char charToCount) =>
                {
                    return default;
                });

            stringAnalyzer.Verify(charOccurs, Times.Once);
        }
    }
}

Usage

While in a test file, type out the name of the interface you wish to generate code for--on its own line. You should be presented with a lightbulb. Using the lightbulb, or the keyboard sequence Ctrl+. you can now generate your basic Moq code by choosing Generate Moq Setups*

Note that for interfaces with generic type arguments, you will need to enter the type arguments in angle brackets before you get code generation.

Example Generic Usage

using Xunit;

namespace Demo;

public interface IGenericService<TSource, TResult>
{
    IEnumerable<TResult> TransformSource(IEnumerable<TSource> items);
}

public class ServiceConsumerTests
{
    [Test]
    public void Go()
    {
        // enter this to get code generation/moq setups:
        IGenericService<string, int>
    }
}

Hints

There are probably bugs, and lots of them. File an issue!

If you don't get the codefix (the lightbulb), it may be one of these reasons:

Lastly

* I reserve the right to change the prompt from Generate Moq Setups to something more fun, or "on-brand"... just sayin'

✔ Happy Testing!