samedi 5 septembre 2015

How do I test inserting via a service in a many-to-many relationship?

How do I test the assignment of a Customer to a Retailer?

I have a number of customers and a number of retailers. A customer can be associated with a number of retailers, and a retailer can have a number of customers associated with it. In essence, a many-to-many relationship.

This relationship is represented in the database as the Customer table, the Retailer table and a RetailerCustomer table which contains a mapping of which customers are assigned to which retailers.

The definition is as follows:

modelBuilder.Entity<Retailer>()
            .HasMany(c => c.Customers)
            .WithMany(p => p.Retailers)
            .Map(mc =>
            {
                mc.ToTable("RetailerCustomer");
                mc.MapLeftKey("RetailerId");
                mc.MapRightKey("CustomerId");
            });

Retailer is defined as:

public class Retailer : Entity
{
    public Retailer()
    {
        Customers = new HashSet<Customer>();
    }

    public string Name { get; set; }
    public ICollection<Customer> Customers { get; set; }
}

Customer is defined as

public class Customer : Entity
{
    public Customer()
    {
        Retailers = new HashSet<Retailer>();
    }

    public string Name { get; set; }
    public string Email { get; set; }

    public ICollection<Retailer> Retailers { get; set; }
}

How can I test the services that insert/update this relationship with Entity Framework?

This is my test method:

[Fact]
public void Can_Add_Customer_To_Retail_Account()
{
    //do I use the RetailerService to register the customer with the Retailer? e.g.
    _retailerService.RegisterNewCustomer(new CustomerDto());

    // or do I use the CustomerService to register the customer? e.g.
    _customerService.RegisterWithRetailer(new CustomerDto());

    // and then what goes on inside either of those service methods?
    // do I get an instance of the retailer and add a new customer e.g
    retailer.Customers.Add(new Customer());
}

Aucun commentaire:

Enregistrer un commentaire