Home > Software design >  Changing Locale for One Unit Test Class
Changing Locale for One Unit Test Class

Time:07-17

I am testing functions which involve calculations with decimal points. I made separate Unit Test Case Classes. One is for testing the comma decimal point "," commonly used in European countries. The other is used for testing calculations with the period decimal point ".".

How can I change the locale for a specific test class? I have tried using this code to change the locale to a country using "," as a decimal separator.

extension NSLocale {
    @objc
    static let currentLocale = NSLocale(localeIdentifier: "en_TR") // Set a needed locale
}

However, it permanently changes the locale for all test cases, including the class for testing ".". I also tried adding the code above to my other test class, but it is not allowed.

Thank you

CodePudding user response:

This is more of a comment, but too big to post as a comment. I think your actual problem is a lack of testability of the actual code. So instead of looking for the way for tests to find a workaround for a testability issue, refactor the actual functions to have locale as an argument, with the default set to Locale.current (or whatever you expect the default to be). For example:

func someCalcWithDecimalPoint(/* some arguments ,*/locale: Locale = Locale.current) {
   // ...
}

or

func someCalcWithDecimalPoint(/* some arguments ,*/withLocale: Locale? = nil) {
   
   let locale = withLocale ?? Locale.current 
   // ...
}

This way your production code doesn't change, but your tests can validate any locale without some shady workarounds, and also your code is readable.

  • Related