如何模拟使用SLF4J Log4J Logger的类?

时间:2019-07-06 15:21:17

标签: java log4j slf4j powermock

我尝试模拟一个类,该类通过另一个类上的Hibernate实例化DatabaseConnection,但是我收到该类中SLF4J错误工厂的错误,但我希望Logger在此Test中运行。如何解决此问题以模拟类,然后成功实例化List和Logger?

我试图模拟课程(Ingredientadminsitration),然后执行以下操作:

PowerMockito.mockStatic(LoggerFactory.class);
        when(LoggerFactory.getLogger(any(Class.class))).
                thenReturn(loggerMock);

Ingredientadministration.java

@Slf4j
public class Ingredientsadministration {
    private ObservableList<Ingredient> zutaten;
    private SQLConnection sqlConnection;
    private static Ingredientsadministration ingredientsadministration;
    private Logger logger;

    private Ingredientsadministration() {
        logger = LoggerFactory.getLogger(this.getClass());
        connectToDB();
        zutaten = FXCollections.observableArrayList(sqlConnection.getZutaten());

    }

    public static Ingredientsadministration getInstance() {
        if (ingredientsadministration == null) {
            ingredientsadministration = new Ingredientsadministration();
        }

        return ingredientsadministration;
    }

MySQLHibernate.java

@Slf4j
public class MySQLConnectHibernate implements SQLConnection {

    private static SessionFactory sessionFactory;
    private Session session;
    private Logger logger;
    private static MySQLConnectHibernate entity;

    private MySQLConnectHibernate() throws ServiceException {
        logger = LoggerFactory.getLogger(this.getClass());
        setup();
    }
   public static MySQLConnectHibernate getInstance() {
        if (entity == null) {
            entity = new MySQLConnectHibernate();
        }
        return entity;
    }

    private void setup() throws ServiceException {
        if (sessionFactory == null) {
            sessionFactory = new        Configuration().configure().buildSessionFactory();
            logger.debug("Create new SessionFactory={}.", sessionFactory);
        }
    }

1 个答案:

答案 0 :(得分:0)

我建议您测试是否记录了特定消息?首先,如果使用@ sl4j,则不必自己实例化记录器。然后应使用Lombok为您执行此操作(log.debug(..))。您可以通过LoggerFactory.getLogger(SomeClass.class);在测试中收到记录器。您可以附加模拟的附加程序,并检查是否将所需的日志条目写入了模拟的附加程序。这是一个简单的示例:https://dzone.com/articles/unit-testing-asserting-line

相关问题