Dawid Cz Dawid Cz - 15 days ago 5
C# Question

UnitTest a function with a DbContext as parameter

Hey I'm try to test this Function.

Edit:

The goal is to write a test that checks if the validate function works correct.

I'm just start with unit testing.

I already tried just to mock the Context but this is not the solution.

It is not working or I made something wrong. ( Connection String error )

What is the correct approach for this Problem ?

Do you have any Idea ?

Thanks for your help.

public static string validate(ProductDBEntities _db)
{
List<string> errorList = new List<string>();


foreach (var error in _db.GetValidationErrors())
{
errorList.Add(error.ValidationErrors.FirstOrDefault().ErrorMessage);
}

if (errorList.Count > 0)
{
string errors = string.Join("\n", errorList);
return errors;
}
return "";
}

Answer

The easiest solution to be able to unit test the logic inside validate would probably be:

public static string validate(List<SomeErrorMessageThing> validationErrors) //Whatever type var error is
        {
            List<string> errorList = new List<string>();

            foreach (SomeErrorMessageThing error in validationErrors)
            {
                errorList.Add(error.ValidationErrors.FirstOrDefault().ErrorMessage);
            }

            if (errorList.Count > 0)
            {
                string errors = string.Join("\n", errorList);
                return errors;
            }
            return "";
        }

Then you don't have to mock anything, you could just send inn your manually crafted list of validationErrors from your test

Comments