简体   繁体   English

编写单元测试以检查登录异常

[英]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. 我想编写单元测试,以在捕获异常时检查log.error函数的工作。 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()). 我想验证是否将使用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. 应该很简单,因为您直接将被调用error()的对象提供给被测方法。

Thus: simply mock that object, for example using Mockito. 因此:只需模拟该对象,例如使用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. 然后,您使用Mockito的验证功能来确保看到带有预期字符串值的对log.error()调用。

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: 使用一个模拟框架来创建IExpressionLogger的模拟,并在测试中验证是否已使用预期参数调用了它的error()方法:

@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");

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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