TakeshiMasukawa-8539 avatar image
0 Votes"
TakeshiMasukawa-8539 asked TakeshiMasukawa-8539 edited

Unit testing ValidationAttribute message localizatiom

I'm developing ASP.NET Core Web API project.

I tried to test a POCO like following:

 public class Poco{
     [Required(ErrorMessageResourceType = typeof(SharedResource), ErrorMessageResourceName = "Required")]
     public string Id {get; set; }

I prepared resource files of some languages for "Required" message.
This perfectly works when I launch the project.

Then, I tried to test this validation message by code below but it always returns ja-JP message (My default locale is ja-JP).

     public class TestPoco
         public void ErrorMessageLocalized()
             Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
             var item = new Poco() { Id = null };
             var validationResultList = new List<ValidationResult>();
             Validator.TryValidateObject(item, new ValidationContext(item), validationResultList);
             var message = validationResultList[0].ErrorMessage;
             Assert.AreEqual("The field [ID] is required", message);

How can I test other languages?


This problem resolved by changing CurrentUICulture instead of CurrentCulture.
CurrentCulture does not affect localization, it affects culture-dependent formatting and parsing.
Thank you for help.

· 2
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Hi,@TakeshiMasukawa-8539 Make sure the resource file has the related translation, then check this link:how-can-i-get-correct-string-localization-when-running-my-unit-tests hope it can help you

1 Vote 1 ·

It worked by adding code below.

 Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-US");

I didn't know changing CurrentCulture has no sense in this case.

Thank you.

0 Votes 0 ·

0 Answers