1

I have a CatalogDbContext class.

I want to use Bogus library to seed fake data into the database that my unit tests will use.

The example provided in bogus's github repo makes use of the HasData method of the CatalogDbContext class to seed data into the tables.

However, I will not want this HasData method to be executed from the API - meaning, the HasData method should only be run if the DBContext is created from the Unit Tests.

Kindly advise how to achieve this?.

using Bogus;
using Catalog.Api.Database.Entities;
using Microsoft.EntityFrameworkCore;

namespace Catalog.Api.Database
{
    public class CatalogDbContext : DbContext
    {
        public CatalogDbContext(DbContextOptions<CatalogDbContext> options) : base(options)
        {
        }
        public DbSet<CatalogItem> CatalogItems { get; set; }
        public DbSet<CatalogBrand> CatalogBrands { get; set; }
        public DbSet<CatalogType> CatalogTypes { get; set; }

        protected override void OnModelCreating(ModelBuilder builder)
        {
            builder.ApplyConfiguration(new CatalogBrandEntityTypeConfiguration());
            builder.ApplyConfiguration(new CatalogTypeEntityTypeConfiguration());
            builder.ApplyConfiguration(new CatalogItemEntityTypeConfiguration());

            FakeData.Init(10);

            builder.Entity<CatalogItem>().HasData(FakeData.CatalogItems);
        }
    }

    internal class FakeData
    {
        public static List<CatalogItem> CatalogItems = new List<CatalogItem>();

        public static void Init(int count)
        {
            var id = 1;

            var catalogItemFaker = new Faker<CatalogItem>()
                .RuleFor(ci => ci.Id, _ => id++)
                .RuleFor(ci => ci.Name, f => f.Commerce.ProductName());
        }

    }
}
Gert Arnold
  • 105,341
  • 31
  • 202
  • 291
blogs4t
  • 2,329
  • 5
  • 20
  • 33
  • 1) This would be an [integration test](https://www.google.com/search?q=what+is+an+integration+test+site%3Astackoverflow.com), not a `unit test`. 2) You should put an interface in front of `CatalogDbContext` and then use `Moq` or similar in your unit tests for `ICatalogDbContext`. 3) If you want an integration test, then the integration test should use a different db connection and then seed the integration db w/ the data from `bogus`. – Metro Smurf Jul 17 '22 at 20:31
  • If you need to reference the same classes from multiple projects, then make a class library project, and have both projects reference that class library. – mason Jul 17 '22 at 20:34
  • SO community, I am still awaiting an answer! – blogs4t Jul 31 '22 at 15:56
  • 1
    You're not *entitled* to getting answers. You had two people interested, you should have savored that by responding. They might have been willing to work with you unto an answer. – Gert Arnold Jul 31 '22 at 16:11

0 Answers0