I have a database with a somewhat complex design, and therefore the issue is complex too.
I communicate with this database through Entity Framework. My codebase looks like this:
- Data layer: Entity Framework, DbContext, Data models.
- Repository layer: Basic CRUD operation providers for the models.
- Logic layer: Business logic.
- Web API layer: Controllers to communicate with the service.
- Test layer: Do Business logic unit tests.
I am in the process to write unit tests and I don't know how to write them properly, or if my business logic layer is just bad... In college, they thought me to do it this way, but I think I might misunderstood the principle behind this pattern...
In my business logic method, I pass a domain object as a parameter, and I use LINQ to 'query' the database to find the needed result. Every method uses the 'queries' as logic. So it's heavily dependent on the query. For example, I need to determine if 2 users are matched with each other or not (like in Tinder)
public bool AreTheyMatched(Profile requestor, Profile requested)
{
var areTheyMatched = ChatRepository.GetAll().Where(x =>
x.Profiles.Contains(requestor) &&
x.Profiles.Contains(requested) &&
x.SYS_ChatType.Type.ToLower() == "match" &&
x.Profiles.Count() == 2).Count() == 1;
return areTheyMatched;
What's considered the best practice here?
- I feel like mocking the query is useless here...
- Also feel like the query should not be part of the logic...
- Mocking the GetAll() method is alright, but since Entity framework generated POCO classes are self-referencing (Chat has Profile list, Profile has Chat entity, and so on...) the set up of mocking would be hard, but possible...
- Should I gather data from the scope of the parameters?
- How can I test the queries to see if they are right at all?
- How can I test business logic at all?
I did the unit tests of validating simple objects while being inserted into the database. That's a no-brainer for me. But this topic's complexity seems to be out of the scope of my current understanding.
CodePudding user response:
Create a list of chat objects with nested profiles that suits your current test case. For example, a list that actually contains a match of the two profiles. Then mock the repository to return this list and assert that a match was found. For another test case, setup the chat list without a match, and assert that no match was found.