[英]JUnit, Mockito and Spring ApplicationContext: Trouble mocking a property
問題描述:我無法為特定的 spring bean 設置一個模擬來返回我的開發框上的正確模擬測試資源位置,而不是運行時 Web 應用程序根。 我確信我的重構做了一些愚蠢的事情。 我希望有人看到它。
我正在使用 Quartz 在 Spring 上執行一項工作。 Quartz 工作運行良好,並且可以正常獲取 Spring 應用程序上下文。 剩下的唯一事情就是為 Web 資源所在的測試或運行時位置連接一個配置屬性。 :
JUnit 4、Spring 3.1、石英、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;
}
}
春天的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 配置中的 Profiles 之后,我做了一些橫向思考。 事實上,我不需要配置文件,這就像在測試模式下進行另一個彈簧配置一樣簡單。
將@MockBean 用於ApplicationContext 而不是@Mock 怎么樣?
我相信您的 ApplicationContext 類是由 @Autowired 在您的實際類中創建的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.