NSubstitute icon indicating copy to clipboard operation
NSubstitute copied to clipboard

Serializing test setups

Open The-Futurist opened this issue 1 month ago • 1 comments

I'm relatively new to mocking (but not .Net) and its been a great help writing unit tests for a new asp.net web api.

As I've been refactoring I found myself wondering how to somehow automate the setup steps by using a setup json file.

For example I just finished this (it centralizes repetitive setup for mocked users for a bunch of unit tests)

        private void Setup_GetUserDataByOrgDefinedId(IDataRepository dataRepository, IEnumerable<UserData?> users, bool ReturnNull = false)
        {
            foreach (var user in users)
            {
                dataRepository.GetUserDataByOrgDefinedId(user.OrgDefinedId).Returns(ReturnNull ? (UserData?)null : user);
            }
        }

        private IEnumerable<UserData?> GenerateTestUsers()
        {
            yield return new() { FirstName = "Alice", LastName = "Smith",   UserId = 1111, OrgDefinedId = "111111111" };
            yield return new() { FirstName = "Steve", LastName = "Coogan",  UserId = 2222, OrgDefinedId = "222222222" };
            yield return new() { FirstName = "Mike",  LastName = "Jones",   UserId = 3333, OrgDefinedId = "333333333" };
            yield return new() { FirstName = "Ralph", LastName = "Edwards", UserId = 4444, OrgDefinedId = "444444444" };
        }

Where test can do:

            Setup_GetUserDataByOrgDefinedId(dataRepository, GenerateTestUsers());

So I was pondering would it be feasible to make this more generic, where I could specify say the interface IDataRepository and the specific method GetUserDataByOrgDefinedId in some general way in a config file, along with the data and the data type UserData? and so on?

On way that might be practical is to generate C# source from some form of JSON definition, that would be less painful that say doing it all with reflection and so on (which is of course possible but perhaps too much work).

I've done quite a lot of T4 template based code generation and had great success with that but was many years ago.

So has this ever come up before? has anyone done anything like it?

The-Futurist avatar Oct 31 '25 15:10 The-Futurist