Code generation to speed up testing in C# using the excellent Moq library.
Demo GIF blurry? Scroll down for a text based demo.
namespace Demo.Lib
{
public interface IStringAnalyzer
{
int CharOccurs(string text, char charToCount);
}
}
using NUnit.Framework; // or Xunit, Microsoft.VisualStudio.TestTools
namespace Demo.Lib.UnitTests
{
public class StringAnalyzerTests
{
[Test]
public void Go()
{
IStringAnalyzer
}
}
}
Generate Moq Setups
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);
}
}
}
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.
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>
}
}
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:
using NUnit.Framework;
using Xunit;
using Microsoft.VisualStudio.TestTools.UnitTesting;
* I reserve the right to change the prompt from Generate Moq Setups
to something more fun, or "on-brand"... just sayin'
✔ Happy Testing!