如何在Spring Junit测试中启用日志记录?

时间:2015-09-16 11:15:15

标签: java spring spring-mvc junit

如何在Spring Junit测试中启用日志记录?我认为在进行测试时找不到web.xml。需要以某种方式告诉Junit哪里有web.xml并且存在日志配置,所以日志将开始工作,我可能会认为Spring配置错误。

我的测试班:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("test-context.xml")
public class DSLCapacityTest {
private MockHttpServletRequest request;
private MockHttpServletResponse response;
@Autowired private DSLCapacity dc;
private AnnotationMethodHandlerAdapter adapter;

@Before
public void setUp() throws Exception {
    request    = new MockHttpServletRequest();
    response   = new MockHttpServletResponse();
    response.setOutputStreamAccessAllowed(true);
    adapter = new AnnotationMethodHandlerAdapter();
}

@Test
@Repeat(2)
public void testGetIndex() throws Exception {
    request.setRequestURI("/dashboard/dsl-capacity/");
    request.setMethod("GET");
    ModelAndView mv = adapter.handle(request, response, dc);
    assertSame("Incorrect message", "dashboard/dsl-capacity/index", mv.getViewName());
}

我的test-context.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns:aop="http://www.springframework.org/schema/aop"
   xmlns:context="http://www.springframework.org/schema/context"
   xmlns:mvc="http://www.springframework.org/schema/mvc"
   xmlns:p="http://www.springframework.org/schema/p"
   xmlns:sec="http://www.springframework.org/schema/security"
   xmlns:tx="http://www.springframework.org/schema/tx"
   xmlns:util="http://www.springframework.org/schema/util"
   xmlns:jee="http://www.springframework.org/schema/jee"
   xmlns:amq="http://activemq.apache.org/schema/core"
   xmlns:jms="http://www.springframework.org/schema/jms"
   xsi:schemaLocation="http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.2.xsd
    http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd
    http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd
    http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-4.0.xsd
    http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
    http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.2.xsd
    http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd
    http://www.springframework.org/schema/jms http://www.springframework.org/schema/jms/spring-jms-4.2.xsd
    http://activemq.apache.org/schema/core http://activemq.apache.org/schema/core/activemq-core-5.8.0.xsd">

<bean id="portalAuthenticator" class="uk.co.powergroup.portal.security.Authenticator">
</bean>

<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
      p:ignoreUnresolvablePlaceholders="false">
    <property name="location">
        <value>file:/etc/portal-frontend/config.properties</value>
    </property>
</bean>

<sec:authentication-manager>
    <sec:authentication-provider ref='portalAuthenticator'/>
</sec:authentication-manager>

<sec:http pattern="/favicon.ico" security="none"/>
<sec:http pattern="/static/**" security="none"/>
<sec:http pattern="/logged-out" security="none"/>
<sec:http pattern="/login" security="none"/>
<sec:http pattern="/**/nologin*" security="none"/>

<sec:http auto-config="false" use-expressions="true">
    <sec:csrf disabled="true"/>
    <sec:intercept-url pattern="/forgot-password" access="isAnonymous()"/>
    <sec:intercept-url pattern="/**" access="isAuthenticated()" />
    <sec:logout logout-url="/logout" logout-success-url="/logged-out"/>
    <sec:form-login login-page="/login" login-processing-url="/login-security-check" authentication-failure-url="/login" />
    <sec:custom-filter position="CONCURRENT_SESSION_FILTER" ref="concurrencyFilter" />
    <sec:session-management session-authentication-strategy-ref="sas"/>
    <sec:custom-filter ref="userValidator" after="FILTER_SECURITY_INTERCEPTOR" />
</sec:http>

<sec:global-method-security pre-post-annotations="enabled" secured-annotations="enabled">
    <sec:expression-handler ref="expressionHandler"/>
</sec:global-method-security>

<bean id="userValidator" class="uk.co.powergroup.portal.security.UserValidator">
</bean>
<bean id="expressionHandler" class="org.springframework.security.access.expression.method.DefaultMethodSecurityExpressionHandler">
    <property name="permissionEvaluator" ref="myPermissionEvaluator"/>
</bean>
<bean id="myPermissionEvaluator" class="uk.co.powergroup.portal.security.PermissionChecker"/>

<bean id="concurrencyFilter" class="org.springframework.security.web.session.ConcurrentSessionFilter">
    <constructor-arg name="sessionRegistry" ref="sessionRegistry" />
    <constructor-arg name="expiredUrl" value="/login" />
</bean>
<bean id="sessionRegistry" class="org.springframework.security.core.session.SessionRegistryImpl"/>
<bean id="sas" class="org.springframework.security.web.authentication.session.ConcurrentSessionControlAuthenticationStrategy">
    <constructor-arg name="sessionRegistry" ref="sessionRegistry" />
    <property name="maximumSessions" value="-1"/>
</bean>

<bean id="myEmf" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
    <property name="dataSource" ref="dataSource"/>
    <property name="persistenceUnitName" value="PORTAL2DB"/>
    <property name="loadTimeWeaver">
        <bean class="org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver"/>
    </property>
</bean>
<bean id="txManager" class="org.springframework.orm.jpa.JpaTransactionManager">
    <property name="entityManagerFactory" ref="myEmf"/>
</bean>

<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
    <property name="url" value="jdbc:mysql://10.10.10.249:3306/portal"/>
    <property name="username" value="portal"/>
    <property name="password" value="twink13s"/>
</bean>

<bean id="jmsFactory" class="org.apache.activemq.pool.PooledConnectionFactory"
      destroy-method="stop">
    <property name="connectionFactory">
        <bean class="org.apache.activemq.spring.ActiveMQConnectionFactory">
            <property name="brokerURL">
                <value>${activemq.uri}</value>
            </property>
            <property name="password">
                <value>${activemq.password}</value>
            </property>
            <property name="userName">
                <value>${activemq.user}</value>
            </property>
        </bean>
    </property>
    <!-- Make this 2.5 minutes in case for some reason the JMS tester job stops (sends every minute so default of 30 seconds too short) -->
    <property name="idleTimeout" value="150000"/>
</bean>

<!-- Spring JMS Template -->
<bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">
    <property name="connectionFactory" ref="jmsFactory"/>
    <property name="receiveTimeout" value="1000"/>
    <property name="sessionTransacted" value="false"/>
</bean>

<bean id="jmsMessageListener" class="uk.co.powergroup.portal.jms.ReplyHandler"/>

<jms:listener-container container-type="default" connection-factory="jmsFactory" acknowledge="auto"
                        concurrency="2-5">
    <jms:listener destination="${activemq.replyQueue}" ref="jmsMessageListener"/>
</jms:listener-container>

<bean id="threadPool" class="uk.co.powergroup.portal.helper.ThreadPool"/>

<bean name="retryTransactionsFilterBean" class="uk.co.powergroup.portal.helper.RetryFilter"/>

<bean id="conversionService"
      class="org.springframework.context.support.ConversionServiceFactoryBean">
    <property name="converters">
        <set>
            <bean class="uk.co.powergroup.portal.converters.PermissionConverter"/>
            <bean class="uk.co.powergroup.portal.converters.RoleConverter"/>
            <bean class="uk.co.powergroup.portal.converters.SuiteConverter"/>
            <bean class="uk.co.powergroup.portal.converters.DataCentreConverter"/>
            <bean class="uk.co.powergroup.portal.converters.DataCentreLocationConverter"/>
            <bean class="uk.co.powergroup.portal.converters.CompanyConverter"/>
            <bean class="uk.co.powergroup.portal.converters.HardwareConverter"/>
            <bean class="uk.co.powergroup.portal.converters.RackConverter"/>
            <bean class="uk.co.powergroup.portal.converters.EquipmentConverter"/>
            <bean class="uk.co.powergroup.portal.converters.PowerDistributionUnitTypeConverter"/>
            <bean class="uk.co.powergroup.portal.converters.TimeZoneDOConverter"/>
            <bean class="uk.co.powergroup.portal.converters.DslLnsBearerTypeConverter"/>
            <bean class="uk.co.powergroup.portal.converters.DslLnsLocationConverter"/>
            <bean class="uk.co.powergroup.portal.converters.DslLnsOrganisationConverter"/>
            <bean class="uk.co.powergroup.portal.converters.DslLnsConverter"/>
            <bean class="uk.co.powergroup.portal.converters.BigDecimalConverter"/>
            <bean class="uk.co.powergroup.portal.converters.PstnNumberDDIConverter"/>
        </set>
    </property>
</bean>

<context:component-scan base-package="uk.co.powergroup.portal.dao.impl"
                        name-generator="uk.co.powergroup.portal.misc.BeanNameGeneratorImpl"/>

1 个答案:

答案 0 :(得分:1)

您可以在测试用例文件中对log4j.properties进行配置,以便为您创建日志。

@BeforeClass
public static void init() {
   PropertyConfigurator.configure("src/configuration/log4j.properties");
}

Java Web容器主要使用web.xml文件,web.xml文件也不属于Spring上下文配置。