JUnit 输出日志到控制台

版权声明:大家好,我是笨笨,笨笨的笨,笨笨的笨,转载请注明出处,谢谢! https://blog.csdn.net/jx520/article/details/88738035

添加依赖到 pom.xml

        <!-- JUnit 输出日志用 -->
        <dependency>
		  <groupId>com.github.stefanbirkner</groupId>
		  <artifactId>system-rules</artifactId>
		  <version>1.16.0</version>
		  <scope>test</scope>
		</dependency>

测试类提个基类

  • 方便获取 bean
  • 方便输出信息到控制台
package com.jerry;

import org.junit.Rule;
import org.junit.contrib.java.lang.system.SystemErrRule;
import org.junit.contrib.java.lang.system.SystemOutRule;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import junit.framework.TestCase;

/**
 * 为了取 bean 方便提个基类。
 */
public class BaseTest extends TestCase {
	//正确输出
    @Rule 
    protected final static SystemOutRule out= new SystemOutRule();
    
    //错误输出
    @Rule
    protected final static SystemErrRule err= new SystemErrRule();
    
	//初始化 spring 上下文;
	protected static ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");

    public <T> T getBean(Class<T> requiredType) {
    	return context.getBean(requiredType);
    }
    
    public Object getBean(String requiredType) {
    	return context.getBean(requiredType);
    }
  
    /**
     * 用于测试中,向控制台输出信息
     * @author jerryjin
     */
    protected static class log{
        public static void out(String msg){
    		System.out.print(msg);
    		out.getLog();
        }
        
        public static void err(String msg){
        	System.err.print(msg);
        	err.getLog();
        }
    }

}

测试类

package com.jerry.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.jerry.BaseTest;
import com.jerry.entity.Book;
import com.jerry.service.IBookService;

public class BookServiceTest extends BaseTest {
	private IBookService bookService= getBean(IBookService.class);
	
	public void testGetById() {
		Book book= bookService.getById(123L);
		assertNotNull(room);
		String jsonString = JSONObject.toJSONString(book);
		log.out(jsonString );
	}
}

猜你喜欢

转载自blog.csdn.net/jx520/article/details/88738035