3

I'm writing a test class for a controller for some lightning components, and I'm a little confused as to what my approach should be. I understand the basic principle of test classes, but I have no experience with it, and I'm already running into an issue.

In my controller (let's call it My_Controller), I have a static method (getCust()) which accepts a String for and Id, queries an account, and returns that account with all the necessary fields. If I insert a test customer in my setup(), how can I bring the Id into my test method in order to properly query for it?

@isTest
private class My_ControllerTest {

    @testSetup
    static void setup() {
        Account cust = new Account(lastname='Testington',firstname='Tess');

        upsert cust;

        System.assertEquals('Testington', cust.lastname);
    }

    @isTest
    public static void testGetCust() {
        Account tmpCust = [SELECT Id, LastName FROM Account WHERE LastName='Testington'];

        Account cust = My_Controller.getCust(tmpCust.Id);
    }
}

This is what I currently have, but it seems backward to have to query before running my query method. Am I missing something obvious, or is this just the only way to test this method?

1 Answer 1

5

You are calling your method correctly. One alternative that might be easier for you to read is to skip the @TestSetup and just generate your data within the test method.

@IsTest
static void testStuff()
{ // no need to make your test method public
    Account record = new Account(/*required fields*/);
    insert record;

    Test.startTest();
        // don't forget to wrap the operation you test in startTest/stopTest
        Account fromController = MyController.myMethod(record.Id);
    Test.stopTest();

    // don't forget your assertions!
}
1

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .