java - JUnit、Mockito 和 Spring ApplicationContext : Trouble mocking a property

标签 java spring mockito applicationcontext

问题描述:我无法为特定 spring bean 设置模拟以返回开发盒上正确的模拟测试资源位置,而不是运行时 Web 应用程序根目录。我确信我在重构时做了一些愚蠢的事情。希望有人能看到。

我正在使用 Quartz 通过 Spring 执行作业。 Quartz 工作工作正常,并且可以正常获取 Spring 应用程序上下文。剩下的唯一事情就是为 Web 资源所在的测试或运行时位置连接一个配置属性。 :

JUnit 4、Spring 3.1、Quartz、Java 8、Mockito

界面:

public interface ITitle {
  /**
   * Gets the root of the application.
   * @return location String
   */
  public String getRuntimeLocation();
}

实现:

@Component("Title")
public class Title implements ITitle, ApplicationContextAware {

  private String location;

  /**
   * Gets the root of the application.
   * @return location String
  */
 public String getRuntimeLocation() {
  String location = "";

  config = getConfig();
  log.debug("Class Title --- Method getRuntimeLocation -- config is " + config );

  location = config.getRuntimeLocation();
  log.debug("Class Title --- Method getRuntimeMethod -- runtime location is " + location );

  return location;
  }
 }

单元测试

import org.junit.Assert;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.generators.analytics.serialised.ITitle;

import java.io.File;

import static org.junit.Assert.assertNotNull;
import static org.mockito.Mockito.when;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {
    "classpath*:/WEB-INF/conf/analytics-context.xml"
})
public class GeneratorTest {

  private AnalyticsGenerator generator;

  @Mock
  private IConfig config;

  @Mock
  private ApplicationContext applicationContext;

  @Mock
  private ITitle title;

  // Set a logger
  private static Logger log =   LoggerFactory.getLogger(GeneratorTest.class);
  private JobExecutionContext job;

  /**
   * Initialises the test parameters.
   */
  @Before
  public void setUp() throws Exception {
      //create a generator object
      generator = new AnalyticsGenerator();

      MockitoAnnotations.initMocks(this);

      when(applicationContext.getBean("Query")).thenReturn(query);
      when(applicationContext.getBean("Config")).thenReturn(config);

            when(config.getRuntimeLocation()).thenReturn(“/Users/me/dev/workarea/");

     generator.executeInternal(ctx);
     }

/**
 * Expected: Json exists
 */
@Test
public void testThatExecuteInternalCreatesAJsonFile() throws JobExecutionException {

    generator.executeInternal(job);

    File returnedJson = new File("classpath:/google-analytics.json");

    Assert.assertNotNull("The JSON file does not exist", returnedJson );
}

/**
 * Remove objects from memory.
 */
@After
public void tearDown() throws Exception {
    generator = null;
}

}

spring xml 文件

<?xml version="1.0" encoding="UTF-8"?>
<!--
  * analytics-context.xml
  *
  * resource configuration file for Google Analytics recommendations integration framework.
  *
  * All custom beans and services must be defined in this file.
  -->
 <beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns:context="http://www.springframework.org/schema/context"
   xmlns:p="http://www.springframework.org/schema/p"
   xmlns:c="http://www.springframework.org/schema/c"
   xmlns:util="http://www.springframework.org/schema/util"
   xmlns:ehcache="http://ehcache-spring-annotations.googlecode.com/svn/schema/ehcache-spring"
   xsi:schemaLocation="http://www.springframework.org/schema/beans
                        http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
                        http://www.springframework.org/schema/context
                        http://www.springframework.org/schema/context/spring-context-3.2.xsd
                        http://www.springframework.org/schema/util
                        http://www.springframework.org/schema/util/spring-util-3.2.xsd
                        http://ehcache-spring-annotations.googlecode.com/svn/schema/ehcache-spring
                        http://ehcache-spring-annotations.googlecode.com/svn/schema/ehcache-spring/ehcache-spring-1.1.xsd">

<context:annotation-config/>

<!--
    START Globally used Google Analytics Query parameters
-->
<bean id="Config" class=“com.generators.analytics.Config">
    <property name="reportLocation" value="/data/runtime/web/assets/generated-list/google-analytics.json"/>
    <property name="runtimeLocation" value="/data/runtime/web/"/>
</bean>

<bean id="configFactory" class="org.springframework.beans.factory.config.ServiceLocatorFactoryBean">
    <property name="serviceLocatorInterface" value=“com.generators.analytics.ConfigFactory" />
</bean>

<alias name="Config" alias="C" />

<bean id="Title" class=“com.generators.analytics.serialised.Title">
    <property name="config" ref="Config"/>
</bean>

<context:component-scan base-package=“com.generators.analytics" />

<!--
    END Globally used Google Analytics Query parameters
 -->

运行测试后,我在日志中得到以下内容:

11:51:43.020 [main] DEBUG com.generators.analytics.serialised.Title - Class Title --- Method getConfig -- applicationContext is org.springframework.context.support.GenericApplicationContext@57f23557: startup date [Tue Jan 24 11:51:31 GMT 2017]; root of context hierarchy
11:51:43.020 [main] DEBUG com.generators.analytics.serialised.Title - Class Title --- Method getConfig -- config is com.generators.analytics.Config@13d9cbf5
11:51:43.020 [main] DEBUG com.generators.analytics.serialised.Title - Class Title --- Method getRuntimeLocation -- config is com.generators.analytics.Config@13d9cbf5
11:51:43.020 [main] DEBUG com.generators.analytics.serialised.Title - Class Title --- Method getRuntimeMethod -- runtime location is /data/runtime/web/

问题是,我在获取预期路径/Users/me/dev/workarea/时是否有任何明显的错误?

我想我需要进行重构才能从方法中提取位置?我不确定如何重构这个特定步骤。

    when(config.getRuntimeLocation()).thenReturn(“/Users/me/dev/workarea/");

最佳答案

我通过创建 spring 配置文件的副本并更改来解决这个问题

<bean id="Config" class="com.generators.analytics.Config">
    <property name="reportLocation" value="/Users/arnout/dev/soton-test/workarea/assets/generated-list/google-analytics.json"/>
    <property name="runtimeLocation" value="/Users/arnout/dev/soton-test/workarea/"/>
</bean>

然后改变

@ContextConfiguration(locations = {
    "classpath*:/WEB-INF/conf/livesite_customer/resources/test-analytics-resource-config.xml"
})
public class GeneratorTest {

在阅读了 Spring 配置中的配置文件后,我做了一些横向思考。事实上,我不需要配置文件,它就像在测试模式下使用另一个 spring 配置一样简单。

关于java - JUnit、Mockito 和 Spring ApplicationContext : Trouble mocking a property,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41829094/

相关文章:

java - Android Timer 时间表与 scheduleAtFixedRate

java - Spring Boot 属性解析不正确

java - Spring + gradle context.xml 在 Windows 中格式错误

jsf-2 - 如何在junit中使用OmniFaces

java - 如何模拟 ResponseEntity

java - 如何使用 mockito 模拟存储库方法而不考虑参数

java - 如何在 PySpark 中启用公平调度程序?

java - hibernate DAO 错误

java - 由于 ClassCastException 而 key 正确时无法在 Java 中打印 LinkedHasMap

java - Spring POST 请求不支持的媒体类型 415