C# Xunit Mocking Db Context (For Testing)

So in my App I use Repositories like.

 public class CommentRepository 
    {
        AppDBContext context;

        public List Comments { get { return this.context.Comments.ToList();  }  }
        public CommentRepository(AppDBContext context)
        {
            this.context = context;
        }
}

The AppDbContext inherits DbContext (part of Entity Framework).

Then in the startup.cs in the ConfigureServices method I add
services.AddDbContext(options => options.UseSqlServer(Configuration["ConnectionStrings:Local"]));

Ok ok... So on to testing.

In my xUnit testing project, with a reference to the main project I can then do a Mock Context and do a database in memory.

Full Example

public class ComplaintTests
    {
        public AppDBContext Context { get; set; }
        public ComplaintRepository ComplaintRepo;
        
        public CommentRepository CommentRepo;

        public ComplaintTests()
        {
            
            /* Create a Memory Database instead of using the SQL */
            var optionsBuilder = new DbContextOptionsBuilder()
                .UseInMemoryDatabase(databaseName: "temp")
                .Options;
            Context = new AppDBContext(optionsBuilder);
            ComplaintRepo = new ComplaintRepository( this.Context);
            CommentRepo = new CommentRepository( this.Context);
        }
    
        
        
        [Fact]
        public void TestTesting()
        {
            //Test that testing is working
            Assert.True(true);
        }
        [Fact]
        public void AddComplaint()
        {
            Complaint complaint = new Complaint() { ID = 1, 
            Contents = "Test Complaint", Completed = false, Create = DateTime.Now };
            bool success = ComplaintRepo.AddComplaint(complaint);
            Assert.True(success);
            // Cleanup
            Context.Database.EnsureDeleted();
        }

A great way to do testing!

More info at Microsoft C# Core In Memory Testing

C# Newtonsoft JSON Serialize and Deserialize of Objects

So after abit of headache. I figured out how to serialize nested objects and deserialize them. This is especially useful for doing Android Development with C#.

So for starters!

Here are the Objects/Models

public class Game

      public class Game
    {
        public Player currentPlayer;

        public Player player1;
        public Player player2;
        public Die die;
        public int currentRound;
        public bool canRoll;
        public bool gameOver;
        public Player winner;
}

public class Player

 [JsonObject(MemberSerialization.OptIn)]
    public class Player
    {
        [JsonProperty("Name")]
        public string Name { get; set; }
        [JsonProperty("Score")]
        public int Score { get; set; }
        [JsonProperty("FinalRollComplete")]
        public bool FinalRollComplete { get; set; }
    }

So the [JsonObject(MemberSerialization.OptIn)] is optional when everything is public. However if I had a protected class I would need it and the JsonProperty in order to store it in my json string.

 public class Die
    {
        [JsonProperty("currentValue")]
        public int currentValue;
}

Ok so now you know the setup, lets talk about the actual serialize and deserialize.

Serialize

string json = JsonConvert.SerializeObject(this.Game, Formatting.Indented);

Deserialize

 Game = JsonConvert.DeserializeObject<Game>(json);

So this also requires you install the NuGet package for Newtonsoft.Json and add the

using Newtonsoft.Json;

at the top