3

I have the current scenario and it's not clear which is the best way to test it.

public class FirstClass {
    public Integer firstMethod() {
        return SecondClass.secondClass_Handler();
    }
}
public class SecondClass {
    public Integer secondClass_Handler() {
        //complex logic here to calculate the Integer returned
    }
}

The method SecondClass.secondClass_Handler is very complex and I have written all test cases to cover it. Now the question is: how can I handle the test cases for the method FirstClass.firstMethod()?

Should I write again all test cases (and duplicate them) or can I skip that becasue the main logic has just tested?

Thanks

2 Answers 2

4

There's a few different ways to approach it, and none of them is definitely the right answer for every single situation.

If firstMethod() is really just one line of code, I'd cover it with a single integration test validating that its action is correct based on the expected value returned by secondClass_Handler() for the given input. But I doubt in your real class that it's one line of code. It may be feasible to cover it with multiple integration tests that don't simply replicate the unit tests you already wrote for secondClass_Handler().

The fuller-scale solution I would use if I wanted a "true" unit test is to dependency inject SecondClass in FirstClass so that you control the return value of secondClass_Handler() and can test firstMethod() in isolation. There's more than one way to implement that; the usual route that I use is interface-based. Inside FirstClass:

private @TestVisible interface ISecondClassDelegate {
    Integer secondClass_Handler();
}

private @TestVisible class SecondClassConcreteDelegate implements ISecondClassDelegate {
    public Integer secondClass_Handler() {
        return SecondClass.secondClass_Handler();
    }
}

@TestVisible private secondClassDelegate = new SecondClassConcreteDelegate();

public Integer firstMethod() {
    return this.mySecondClassHandler.secondClass_Handler();
}

then, in the unit test,

private class MockSecondClassDelegate implements FirstClass.ISecondClassDelegate {
    public Integer secondClass_Handler() {
        return 1; // or what have you.
    }
}

@isTest
public static void testFirstMethod() {
    FirstClass f = new FirstClass();
    f.secondClassDelegate = new MockSecondClassDelegate();

    // test logic for a return value of 1.
}

That's a fair amount of boilerplate, and whether or not it's appropriate and needed to effectively validate the behavior of firstMethod() is a decision you'll have to make based on your understanding of the code and its interaction with secondClass_Handler().

0
0

You can skip them for unit tests, although some organizations prefer to write "functional" unit tests as well (to test end-to-end functionality). This ensures that there's no governor limit issues, etc.

You must log in to answer this question.

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