Uncategorized

Unit Testing of Queries involving LINQ Joins with Fakes C#

Recently we encountered a scenario where we had join queries involved in our code.

So, the requirement we had to pass the data of the joined entities accordingly which would satisfy the code logic in our Unit Test.

But it was not as easy as we thought as there is a tricky part involved there.

Sample Plugin Code for which we will be creating Unit Test:

1

As you can see in our code we are querying the Contact entity and using Joins with the Account entity to read the Account Name along with Contact Last Name.

So, we will be adding the below code to send the record in the Response:

2

But the problem here was How to send the joined Entity’s value as if we don’t pass any value then it was showing null value in the returned query results.

So, we thought of going for AliasedValue concept. So we decided to pass “a.name” field in the attributes and set the value as below as in our Linq query we had used “join a” in the Linq query:

contactObj.Attributes[“a.name”] = new AliasedValue(Account.EntityLogicalName, “name”, “Test Sid”);

But still, it didn’t work. On further spending more time and debugging the request we found the tricky part involved:

3

So as you can see the Entity Alias name involved is “a_0” and not “a” so we changed the code to “a_0.name” as below and it worked like a charm 😊

4

The above example shows how it works when one join is involved. Just for more curiosity, I tried with below multiple joins query:

5.png

So, it returns the link entity information as below:

For 1st Join on Contact

6.png

For 2nd Join on Lead

7.png

From the above results, I came to know that joins in LINQ works in a bit different way!!

The entity alias name is populated based on the joins order in your LINQ Query starting from 0 and increasing further if the query contains more joins along with the variable used for the respective entities.

Hope this helps and ease your Unit Testing with Fakes.

Leave a comment