如何为将字符串打印到控制台并使用 Spring 框架的主方法编写 Junit "Hello, World!"



我是Spring的初学者,有以下代码:

import org.springframework.stereotype.Service;
@Service("helloWorldService")
public class HelloWorldService {
private String name = "Hello World";
public String getName() {
return this.name;
}
}

/** * 你好类启动这个Java应用程序 */

public class Hello {
private static final Logger LOGGER = Logger.getLogger(Hello.class.getName());
@SuppressWarnings("resource")
public static void main(final String[] args) {
final ApplicationContext context = new ClassPathXmlApplicationContext(
"applicationContext.xml");
final HelloWorldService service = (HelloWorldService) context.getBean("helloWorldService");
final String message = service.getName();
Hello.LOGGER.info(message);
}
}

我需要如何编写测试?因为如果我使用 this.log.getLog ((,那么 Junit 中的实际输出将留空以供比较。

我认为问题是关于如何验证某些值是否实际写入日志。如果您使用的是 Spring Boot,则可以使用 OutputCapture 来验证已写入控制台的内容。Un 示例在 Spring Boot 文档中给出。

但是,一般来说,单元测试应该允许根据预期操作验证某些操作的实际结果。HelloWorldServicegetName的方法非常适合此类测试,因为您可以添加 Junit(或其他框架(断言,即返回值等于您的预期值。

最新更新