I am working on a web api project in asp.net. I have decided to put the data access layer aside and focus on the business layer, but for that i have to find a way to mimic the data access layer.
I am working with repositories, my application is a bit more complicated than that but for now lets say that i have two domain objects, User and Ticket:
class User {
public int Id { get; set; }
public string Name { get; set; }
public IList<Ticket> Tickets { get; set; }
}
class Ticket {
public int Id { get; set; }
public int Type { get; set; }
public string Name { get; set; }
public User Owner { get; set; }
}
I have the user test repository:
class UserTestRepository : IUserRepository {
private TestDataContext context;
public UserTestRepository (TestDataContext Context) {
this.context = Context;
}
public User GetById (int Id) {
return context.Users.Where(u => u.Id == Id).Single();
}
public void Add (User User) {
context.AddUser(User);
}
}
And also the ticket test repository which looks the same. The TestDataContext looks something like that:
class TestDataContext {
public IList<User> Users { get; set; }
public IList<Ticket> Ticets { get; set; }
private int userCount;
private int ticketCount;
public TestDataContext () {
userCount = 0;
ticketCount = 0;
Users = new List<User>();
Tickets = new List<Ticket>();
Seed(); // Not implemented yet...
}
public void AddUser (User User) {
User.Id = userCount;
userCount++;
Users.Add(User);
}
public void UpdateUser (User User) {
int index = Users.IndexOf(Users.Where(u => u.Id == User.Id).First());
Users[index] = User;
}
public void DeleteUser (User User) {
Users.Remove(Users.Where(u => u.Id == User.Id).First());
}
// Same three methods for Tickets...
}
Now lets say that i want to add a new Ticket to user with id 3, i would do this:
Ticket ticket = new Ticket () {
Type = 1,
Name = "My Ticket",
Owner = new User () { Id = 3 }
};
TicketsRepository.Add(ticket);
The problem is that when i fetch the user with id 3, i would want to see this ticket that i inserted in the user's Tickets list.
I though of doing something like that:
// This is in TestDataContext
public void AddTicket (Ticket Ticket) {
Ticket.Id = ticketCount;
ticketCount++;
Tickets.Add(Ticket);
int userIndex = Users.IndexOf(Users.Where(u => u.Id == Ticket.User.Id).First());
Users[userIndex].Tickets.Add(Ticket);
}
But the same i will have to do for updating and deleting, and for more complicated data relations in would be a really difficult task.
So my question is, am i doing it right? Is this how i supposed to test my data layer?
I don't want to just test data fetching, i want to test inserting and deleting because those i also very important functions of my application.
Thank you
Aucun commentaire:
Enregistrer un commentaire