-1

So I have a function like this that will call other function and pass in a string that will be returned based on different condition. They will always use a normal string, however if certain conditions are met then the special string will be used to passed in to the other function instead.

public async Task Func(context)
{
    var stringToBeUsed  = GetNormalString(context);

    if (FirstConditionFulfilled(context) && 
        (SecondConditionFulfilled(context))
    {
        stringToBeUsed  = GetSpecialString(context);
    }

    await DoSthElse(context, stringToBeUsed );
}

This is the get normal string function

private string GetNormalString(context)
        => context.HttpContext.DoSthToGetNormalString().ToString();

And this is the get special string function

private string GetSpecialString(context)
        => context.HttpContext.DoSthToGetSpecialString().ToString;

I wonder how should I set up the unit test to see if certain conditions are met, the stringToBeUsed will be the special string, otherwise, will be the normal string?

Alexander Petrov
  • 13,457
  • 2
  • 20
  • 49
Noelia
  • 89
  • 10

1 Answers1

2

Your Function does two things:

  1. get the special string and then

  2. do something with it.

That makes it hard to test. Why dont you put the getting of the string in a new function and now each function only does one thing that you can test easier:

public string GetTheRightString(context){ //new function you can easily test
    var stringToBeUsed  = GetNormalString(context);
    if (FirstConditionFulfilled(context) && 
        (SecondConditionFulfilled(context))
    {
        stringToBeUsed  = GetSpecialString(context);
    }

    return stringTobeUsed;
}

public async Task Func(context)
{
    var stringToBeUsed  = GetTheRightString(context);
    await DoSthElse(context, stringToBeUsed );
}

But you probably dont want to make that method public. If you keep it private and you want to test it (which is a topic some people are very dogmatic about that you should never do that. I disagree) look here. Or you put the method in a new class and make that public/internal. There is no right or wrong here in my opinion.

HrkBrkkl
  • 613
  • 5
  • 22
  • Thanks for your answer, breaking the function into 2 smaller functions seems to be the right approach. However, I would prefer not to have the function GetTheRightString be public since no other class would need to use it so I do not want to expose its detail. – Noelia Sep 08 '21 at 09:05
  • @Noelia i added some info. Maybe that helps you how to go from there – HrkBrkkl Sep 08 '21 at 09:29
  • By the way @HrkBrkkl, I was wondering if the normal string use context.HttpContext.Request.Query[string].ToString(); and context.HttpContext.User.Claims.FirstOrDefault(); how can I unit test it? I consider using httpContextMock.Setup(x => x.Request.Query().Returns(normalString); And what should I Assert it equals to? – Noelia Sep 08 '21 at 10:13