Skip to content

Instantly share code, notes, and snippets.

@tyoshikawa1106
Created October 16, 2016 11:27
Show Gist options
  • Save tyoshikawa1106/451b78f23bc1d0d81a44c71c7803ee6b to your computer and use it in GitHub Desktop.
Save tyoshikawa1106/451b78f23bc1d0d81a44c71c7803ee6b to your computer and use it in GitHub Desktop.
global with sharing class UserWebService {
WebService static String changeLanguage() {
try {
// ログインユーザの情報取得
User user = getLoginUserInfo();
// 現在の言語の判定と変更後の言語をセット
user = setUserLanguage(user);
// 更新
update user;
} catch (Exception e) {
return 'システムエラーが発生しました。';
}
return '';
}
private static User getLoginUserInfo() {
return [
SELECT
Id
,Name
,LanguageLocaleKey
,LocaleSidKey
FROM
User
WHERE
Id =: UserInfo.getUserId()
LIMIT 1
];
}
private static User setUserLanguage(User user) {
if (user.LanguageLocaleKey.equals('ja')) {
user.LanguageLocaleKey = 'en_US';
user.LocaleSidKey = 'en_US';
} else {
user.LanguageLocaleKey = 'ja';
user.LocaleSidKey = 'ja';
}
return user;
}
}
@isTest
private class UserWebServiceTest {
// テスト実行ユーザ取得
private static User testAdminUser = [SELECT Id,LanguageLocaleKey,LocaleSidKey
FROM User WHERE Id =: UserInfo.getUserId() LIMIT 1];
static testMethod void changeLanguageTest1() {
System.runAs(testAdminUser) {
// 処理前の言語の値取得
String defaultLocaleSidKey = testAdminUser.LocaleSidKey;
Test.startTest();
// WebService実行
String result = UserWebService.changeLanguage();
Test.stopTest();
// エラーが発生していないかチェック
System.assertEquals(String.isEmpty(result), true);
// 更新後のユーザ言語チェック
User resultUser = [SELECT Id,LocaleSidKey FROM User WHERE Id =: testAdminUser.Id LIMIT 1];
// 処理前と処理後で値が異なることを確認
System.assertNotEquals(resultUser.LocaleSidKey, defaultLocaleSidKey);
}
}
static testMethod void changeLanguageTest2() {
System.runAs(testAdminUser) {
// 処理前の言語の値取得
String defaultLocaleSidKey = testAdminUser.LocaleSidKey;
Test.startTest();
// WebService実行
String result = UserWebService.changeLanguage();
// WebService再実行
result = UserWebService.changeLanguage();
Test.stopTest();
// エラーが発生していないかチェック
System.assertEquals(String.isEmpty(result), true);
// 更新後のユーザ言語チェック
User resultUser = [SELECT Id,LocaleSidKey FROM User WHERE Id =: testAdminUser.Id LIMIT 1];
// 処理前と処理後で値が同じことを確認
System.assertEquals(resultUser.LocaleSidKey, defaultLocaleSidKey);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment