찬란하게

Salesforce Apex Testing 본문

SaaS/Salesforce Certi

Salesforce Apex Testing

체리핫 2024. 11. 29. 22:34

1. Apex Test Class Essentials

  • Purpose: To verify Apex logic works correctly and adheres to best practices.
  • Best Practices:
    • Cover at least 75% of Apex code.
    • Use assertions (System.assert) to validate expected outcomes.
    • Ensure test data isolation (each test should run independently).
  • Annotations:
    • @isTest: Marks a class or method as a test.
    • @testSetup: Prepares reusable test data for all methods in the class.
    • isTest(SeeAllData=true): Allows access to organization data (use sparingly).

2. @testSetup Annotation

  • Key Features:
    • Executes once per test class.
    • Test data created is accessible to all test methods.
    • Saves system resources and avoids data duplication.
    • Cannot be used with isTest(SeeAllData=true).
    • Data can be updated or modified in individual test methods.

3. Testing Best Practices

  • Use Factory Classes:
    • Centralize test data creation for reusability.
  • Avoid Dependency on Real Data:
    • Always use mock or generated data for tests.
    • Avoid SeeAllData=true unless absolutely necessary.
  • Assertions:
    • Use System.assert or System.assertEquals to validate logic.
    • Verify governor limits using Limits class when required.

4. Governor Limits in Tests

  • Test methods enforce governor limits, ensuring that your code can handle system constraints.
    Examples:
    • SOQL/DML limits.
    • CPU time and heap size.

5. Common Apex Test Patterns

  • Unit Testing:
    • Focuses on testing individual methods.
  • Integration Testing:
    • Tests how different parts of the system work together.
  • Mocking:
    • Use HttpCalloutMock for testing HTTP callouts.
    • Use Test.loadData() to load static resources for test records.

6. Negative Testing

  • Test for edge cases, errors, and exceptions:
    • Example: Test behavior when encountering null inputs or invalid data.

7. Salesforce-Specific Testing Tools

  • Test.startTest() / Test.stopTest():
    • Isolate a portion of code and reset governor limits for accurate testing.
  • Test.setMock():
    • Mock external callouts for test coverage without performing actual callouts.

8. Test Execution and Debugging

  • Use the Developer Console, VS Code, or Setup UI to execute test classes.
  • Analyze results using the Apex Test Execution page.
  • Debug failures with logs and debug statements (System.debug()).

1. Apex 테스트 필수사항

  • 목적: Apex 로직이 올바르게 작동하고 모범 사례를 준수하는지 확인합니다.
  • 모범 사례:
    • Apex 코드의 75% 이상을 포함합니다.
    • 예상 결과를 검증하려면 **어설션(System.assert)**을 사용하세요.
    • 테스트 데이터 격리를 보장합니다(각 테스트는 독립적으로 실행되어야 함).
  • Annotation:
    • @isTest: 클래스나 메서드를 테스트로 표시합니다.
    • @testSetup: 클래스의 모든 메소드에 대해 재사용 가능한 테스트 데이터를 준비합니다.
    • isTest(SeeAllData=true): 조직 데이터에 대한 액세스를 허용합니다(아껴서 사용).

2. @testSetup 주석

  • 주요 기능:
    • 테스트 클래스당 한 번 실행됩니다.
    • 생성된 테스트 데이터는 모든 테스트 방법에서 액세스 가능합니다.
    • 시스템 리소스를 절약하고 데이터 중복을 방지합니다.
    • isTest(SeeAllData=true)와 함께 사용할 수 없습니다.
    • 데이터는 개별 테스트 방법으로 업데이트되거나 수정될 수 있습니다.

3. 모범 사례 테스트

  • 팩토리 클래스 사용:
    • 재사용성을 위해 테스트 데이터 생성을 중앙 집중화합니다.
  • 실제 데이터에 대한 의존성 방지:
    • 테스트에는 항상 모의 데이터 또는 생성된 데이터를 사용하십시오.
    • 꼭 필요한 경우가 아니면 SeeAllData=true를 사용하지 마세요.
  • 주장:
    • 'System.assert' 또는 'System.assertEquals'를 사용하여 로직을 검증하세요.
    • 필요한 경우 Limits 클래스를 사용하여 거버너 제한을 확인하세요.

4. 테스트의 거버너 제한

  • 테스트 방법은 거버너 제한을 적용하여 코드가 시스템 제약 조건을 처리할 수 있는지 확인합니다.
    예:
    • SOQL/DML 제한.
    • CPU 시간 및 힙 크기.

5. 일반적인 Apex 테스트 패턴

  • 단위 테스트:
    • 개별 방법을 테스트하는 데 중점을 둡니다.
  • 통합 테스트:
    • 시스템의 다양한 부분이 어떻게 함께 작동하는지 테스트합니다.
  • 조롱:
    • HTTP 콜아웃을 테스트하려면 'HttpCalloutMock'을 사용하세요.
    • 테스트 기록에 대한 정적 리소스를 로드하려면 Test.loadData()를 사용하세요.

6. negative 테스트

  • 극단적인 경우, 오류 및 예외에 대한 테스트:
    • 예: null 입력 또는 유효하지 않은 데이터가 발생할 때 동작을 테스트합니다.

7. Salesforce 전용 테스트 도구

  • Test.startTest() / Test.stopTest():
    • 정확한 테스트를 위해 코드의 일부를 분리하고 거버너 제한을 재설정합니다.
  • Test.setMock():
    • 실제 콜아웃을 수행하지 않고 테스트 적용 범위를 위한 모의 외부 콜아웃입니다.

8. 테스트 실행 및 디버깅

  • 개발자 콘솔, VS Code 또는 Setup UI를 사용하여 테스트 클래스를 실행합니다.
  • Apex 테스트 실행 페이지를 사용하여 결과를 분석합니다.
  • 로그 및 디버그 문(System.debug())으로 인한 디버그 실패.



'SaaS > Salesforce Certi' 카테고리의 다른 글

Salesforce 주요 Annotation  (1) 2024.11.30
Salesforce <-데이터교환-> 외부시스템  (0) 2024.11.29
Salesforce WorkFlow VS Flow  (1) 2024.11.28
Salesforce 자동화도구 총정리  (0) 2024.11.27
Salesforce Flow VS Process Builder  (0) 2024.11.27