简体   繁体   English

如何测试不返回任何内容的方法?

[英]How to test a method which does not return anything?

I want to test following code.我想测试以下代码。 But as it does always return a message migration completed therefore, how would I be sure if exception was thrown and if it went through catch block.但由于它总是返回消息迁移已完成,因此我如何确定是否引发异常以及它是否通过了 catch 块。

In simple words I do not have anything to assert.简单来说,我没有什么要断言的。

Note: I am not allowed to append an extra message to my return message, it should always be migration completed注意:我不允许将 append 额外的消息发送到我的返回消息中,它应该始终是迁移完成

if (sourceCampaign.getId() > 0 || collect.size() > 0) {
    throw new IllegalStateException("ids are positive"); 

} catch(IllegalStateException e) {        
    logger.error("error", "Migration error, IDs are positive");                             
}

return("migration completed");

Please be patient as I am new in programing world.请耐心等待,因为我是编程世界的新手。

First of all, this method should be improved.首先,这种方法应该改进。 Don't use exceptions for control flow.不要对控制流使用异常。 Since the exception is thrown and caught under a specific condition, just use that condition:由于在特定条件下抛出并捕获异常,因此只需使用该条件:

if (sourceCampaign.getId() > 0 || collect.size() > 0) {
    logger.error("error", "Migration error, IDs are positive");
}
return("migration completed");

Now, as for testing, there are two things you'd need to cover:现在,至于测试,您需要涵盖两件事:

  1. The method returns the expected result (this is an easy test, since this method always ever returns the exact same thing).该方法返回预期的结果(这是一个简单的测试,因为该方法总是返回完全相同的东西)。
  2. The method invokes expected functionality.该方法调用预期的功能。

The second one is right here:第二个就在这里:

logger.error("error", "Migration error, IDs are positive");

You'd need to test that, when provided which souceCampaign and/or collect values which meet the expected criteria, that the error() method is invoked on logger .您需要测试,当提供哪个souceCampaign和/或collect满足预期标准的值时,在logger上调用error()方法。 You would do this by supplying the object with a mock instance for logger .您可以通过为 object 提供logger模拟实例来做到这一点。

Java has a variety of mocking libraries available (I've used Mockito in the past and it's done the job well). Java 有各种可用的 mocking 库(我过去使用过 Mockito 并且做得很好)。 And depending on your architecture you may also want to start learning about Dependency Injection.根据您的架构,您可能还想开始学习依赖注入。 (Or at least the Dependency Inversion Principle, if not any particular Dependency Injection framework.) But with a mocked logger you can assert that specific operations were invoked on that mock. (或者至少是依赖倒置原则,如果不是任何特定的依赖注入框架。)但是使用模拟logger ,您可以断言在该模拟上调用了特定操作。

The way the code is written doesn't make it easy to test.编写代码的方式并不容易测试。 An alternative answer to the ones you have already received is to rewrite it to something more testable:您已经收到的答案的替代答案是将其重写为更可测试的内容:

try {
   validate( sourceCampaign, collect);
} catch(IllegalStateException e) {
   manage(e);
}
finally {
   return("migration completed");
}

public void validate(...) throws IllegalStateException {
   if (sourceCampaign.getId() > 0 || collect.size() > 0) {
     throw new IllegalStateException("ids are positive"); 
   }
}

public void manage(Exception e) {
   logger.error("error", "Migration error, IDs are positive");
}

Now that they are separated in different methods, you can test that each part works in the expected way and you can also mock them by extending the original class.现在它们以不同的方法分开,您可以测试每个部分是否按预期方式工作,还可以通过扩展原始 class 来模拟它们。

One way to test that the validate method throw an exception in JUnit 4 is to use the rule ExpectedException :测试validate方法是否在 JUnit 4 中引发异常的一种方法是使用规则ExpectedException

    @Rule
    public ExpectedException thrown = ExpectedException.none();

    @Test
    public void testIllegalStateException() throws Exception {
        thrown.expect( IllegalStateException.class );
  
        ...
        new ClassName().validate( sourceCampaign, collect );
    }

There is no easy way, as far as I know, to test with a unit test that the log message is printed.据我所知,没有简单的方法来测试打印日志消息的单元测试。

Note that I don't think you need to throw an exception in this case and you could log the error if the condition is not met.请注意,我认为在这种情况下您不需要抛出异常,如果不满足条件,您可以记录错误。 But somebody else already provided that answer.但是其他人已经提供了这个答案。

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

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