ステップ 1: 単体テストを作成する
単体テストのメソッドは引数を取らず、データベースにデータをコミットすることもありません。DeleteRestrictInvoice トリガの単体テストを作成するには、次の手順を実行します。
-
[あなたの名前] の下にある開発者コンソールまたはクイックアクセスメニュー (
) を開きます。 - をクリックします。
- ポップアップに、クラス名として 「TestDeleteRestrictInvoice」と入力し、[OK] をクリックします。
- 自動生成されたコードを新しい Apex クラスエディタで次のコードで置き換え、[CTRL+S] を押してクラスを保存します。
ソースコードについては、https://gist.github.com/3605669を参照してください。
1@isTest
2private class TestDeleteRestrictInvoice {
3
4 // Invoice generator, with or without a Line Item
5 static Invoice__c createNewInvoice(Boolean withLineItem) {
6 // Create test Merchandise
7 Merchandise__c merchandise = new Merchandise__c(
8 Name = 'Test Laptop',
9 Quantity__c = 1000,
10 Price__c = 500
11 );
12 insert merchandise;
13
14 // Create test Invoice
15 Invoice__c invoice = new Invoice__c();
16 insert invoice;
17
18 // Create test Line Item and insert it into the database, if withLineItem == true
19 if (withLineItem) {
20 Line_Item__c item = new Line_Item__c(
21 name = '1',
22 Quantity__c = 1,
23 Merchandise__c = merchandise.Id,
24 Invoice__c = invoice.Id
25 );
26 insert item;
27 }
28 return invoice;
29 }
30
31 // Single row Invoice with no Line Items => delete
32 static testMethod void verifyInvoiceNoLineItemsDelete(){
33 // Create test Invoice and insert it
34 Invoice__c invoice = createNewInvoice(false);
35
36 // Delete the Invoice, capture the result
37 Database.DeleteResult result = Database.delete(invoice, false);
38
39 // Assert success, because target Invoice doesn't have Line Items
40 System.assert(result.isSuccess());
41 }
42
43 // Single row Invoice with Line Items => delete restrict
44 static testMethod void verifyInvoiceLineItemsRestrict(){
45 // Create test Invoice and Line Item and insert them
46 Invoice__c invoice = createNewInvoice(true);
47
48 // Delete the Invoice, capture the result
49 Database.DeleteResult result = Database.delete(invoice, false);
50
51 // Assert failure-not success, because target Invoice has tracks
52 System.assert(!result.isSuccess());
53 }
54
55 // Bulk delete of Invoice, one without Line Items, another with
56 static testMethod void verifyBulkInvoiceDeleteRestrict(){
57 // Create two test Invoices, one with and without a Line Item
58 Invoice__c[] invoices = new List<Invoice__c>();
59 invoices.add(createNewInvoice(false));
60 invoices.add(createNewInvoice(true));
61
62 // Delete the Invoices, opt_allOrNone = false, capture the results.
63 Database.DeleteResult[] results = Database.delete(invoices, false);
64
65 // Assert success for first Invoice
66 System.assert(results[0].isSuccess());
67 // Assert not success for second Invoice
68 System.assert(!results[1].isSuccess());
69 }
70}もうひとこと...
コードのコメントでは、テストメソッドの要点を説明します。トリガを作成してテストする場合、トリガは、単一行と一括のどちらのトリガステートメントからでも起動されることを覚えておくことが重要です。単体テストの構築に関しては、次のいくつかの重要事項を理解しておく必要があります。
- テストに使用するコードのみを含むクラスまたは個別のメソッドを定義するには、@isTest アノテーションを使用します。
- テストクラスは最上位クラスである必要があります。
- 単体テストのメソッドは、@isTest アノテーションまたは testMethod キーワードを使用して定義された静的メソッドです。