简体   繁体   中英

Writing unit-test to check logging in exception

I want to write unit-test to check work of log.error function when exception is catched. I have this class:

class SalesMasterModelDateSequenceWrapper {

public static List<EMDate> getDatesClass(IAnalysisExpressionContext context, IContract contract, EMDate analysisDate, IExpressionLogger log, Lookup lookup) {

    try {

        StringBuilder scenarioName = new StringBuilder();
        scenarioName.append(contract.getStringFDA(lookup.getServerFDA("NewContractsForecastName").toLowerCase()));
        if (scenarioName.toString().length()==0) return new ArrayList<>();
        scenarioName.append("_").append(analysisDate.year()).append(analysisDate.month()).append(analysisDate.day());
        if (!context.getScenarioName().contains(scenarioName.toString())){
            return Arrays.asList(contract.getValueDate());
        }
    }
    catch (Exception e) {
        StringBuilder sb = new StringBuilder();
        sb.append("SalesMasterModelDateSequence: ").append(e.getMessage()).append("\n");
        for (StackTraceElement stackTraceElement : e.getStackTrace())
        {
            sb.append(stackTraceElement.toString()).append("\n");
        }
        log.error(sb.toString());
    }
    return new ArrayList<>();

}

I want to verify that I'll take the result of log.error(sb.toString()). Can somebody help with this issue? Thanks in advance.

Should be pretty straight forward, as you directly provide the object on which error() is called to the method under test.

Thus: simply mock that object, for example using Mockito.

And then you use the verify functionality of Mockito to ensure that you see that call to log.error() with the expected string value.

You can find many examples how to do that; for example here .

Given your specific example, you could even write your own stub implementation of that logging interface; and have that code simply remember any strings given to it. So that you can afterwards simply ask the stub to return that string passed into it.

Unse a mocking framework to create a mock of IExpressionLogger and in your test verify that its error() method has been called with the expected parameter:

@Rule 
public MockitoRule mockitoRule = MockitoJUnit.rule(); 
@Mock
private IExpressionLogger expressionLogger;
@Mock
private Lookup lookup;
@Test
public void exceptionMessageLoggedAsError() {
 doThrow(new RuntimeException("UnitTest").when(lookup).getServerFDA(anyString());

  new SalesMasterModelDateSequenceWrapper(/* other parameters */,expressionLogger, lookup).getDatesClass(/* parameters */);

  verify(expressionLogger).error("the expected message containing substring 'UnitTest' from Exception");

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM