简体   繁体   中英

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 "";
        }

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM