当我运行我的单元测试时,它会调用我的计划任务.我想防止这种行为,这是由我@EnableScheduling在主应用程序配置上的事实引起的.
如何在单元测试中禁用此功能?
我遇到过这个问题/答案,建议设置个人资料?
不确定我会怎么做?或者如果它有点矫枉过正?我正在考虑为我的单元测试使用单独的AppConfiguration,但是当我这样做时,感觉就像是重复代码两次?
@Configuration
@EnableJpaRepositories(AppConfiguration.DAO_PACKAGE)
@EnableTransactionManagement
@EnableScheduling
@ComponentScan({AppConfiguration.SERVICE_PACKAGE,
AppConfiguration.DAO_PACKAGE,
AppConfiguration.CLIENT_PACKAGE,
AppConfiguration.SCHEDULE_PACKAGE})
public class AppConfiguration {
static final String MAIN_PACKAGE = "com.etc.app-name";
static final String DAO_PACKAGE = "com.etc.app-name.dao";
private static final String ENTITIES_PACKAGE = "com.etc.app-name.entity";
static final String SERVICE_PACKAGE = "com.etc.app-name.service";
static final String CLIENT_PACKAGE = "com.etc.app-name.client";
static final String SCHEDULE_PACKAGE = "com.etc.app-name.scheduling";
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory(){
// stripped code for question readability
}
// more app config code below etc
}
Run Code Online (Sandbox Code Playgroud)
单元测试示例.
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes={AppConfiguration.class})
@Transactional …Run Code Online (Sandbox Code Playgroud) 我是Spring的新手,这也是我在StackOverflow上的第一个问题,所以我将尝试尽可能地理解这一点.
我正在尝试在本教程中使用Spring和Maven创建一个Web服务客户端:我收到此错误:导入org.springframework.test.context.junit4无法解析
这是我的代码:
package demo;
import hello.WsClientApplication;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; //this won't import
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = WsClientApplication.class)
public class WsClientApplicationTests {
@Test
public void contextLoads() {
}
}
Run Code Online (Sandbox Code Playgroud)
pom.xml如果你需要它,这是我的.
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.springframework</groupId>
<artifactId>gs-consuming-web-service</artifactId>
<version>0.1.0</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.2.3.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.ws</groupId>
<artifactId>spring-ws-core</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<!-- tag::wsdl[] -->
<plugin>
<groupId>org.jvnet.jaxb2.maven2</groupId>
<artifactId>maven-jaxb2-plugin</artifactId>
<version>0.12.3</version>
<executions>
<execution>
<goals> …Run Code Online (Sandbox Code Playgroud) 为什么我的弹簧测试设置失败,下面没有如此有用的错误消息?所有建议表示赞赏.
JUnit输出
java.lang.NoClassDefFoundError: org/junit/runners/model/MultipleFailureException
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.withAfterClasses(SpringJUnit4ClassRunner.java:188)
at org.junit.runners.ParentRunner.classBlock(ParentRunner.java:145)
at org.junit.runners.ParentRunner.run(ParentRunner.java:235)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run (SpringJUnit4ClassRunner.java:163)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
Caused by: java.lang.ClassNotFoundException: org.junit.runners.model.MultipleFailureException
at java.net.URLClassLoader$1.run(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
... 10 more
Run Code Online (Sandbox Code Playgroud)
控制台输出
INFO:org.springframework.test.context.support.DefaultTestContextBootstrapper - 从位置[META-INF/spring.factories]加载默认的TestExecutionListener类名:[org.springframework.test.context.web.ServletTestExecutionListener,org.springframework.test. context.support.DependencyInjectionTestExecutionListener,org.springframework.test.context.support.DirtiesContextTestExecutionListener,org.springframework.test.context.transaction.TransactionalTestExecutionListener,org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener] INFO:org.springframework.test. context.support.DefaultTestContextBootstrapper - 无法实例化TestExecutionListener [org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener].指定自定义侦听器类或使默认侦听器类(及其所需的依赖项)可用.违规类:[org/springframework/transaction/interceptor/TransactionAttribute] INFO:org.springframework.test.context.support.DefaultTestContextBootstrapper - 无法实例化TestExecutionListener [org.springframework.test.context.transaction.TransactionalTestExecutionListener].指定自定义侦听器类或使默认侦听器类(及其所需的依赖项)可用.违规类:[org/springframework/transaction/interceptor/TransactionAttributeSource] INFO:org.springframework.test.context.support.DefaultTestContextBootstrapper - 使用TestExecutionListeners:[org.springframework.test.context.web.ServletTestExecutionListener@76959acc,org.springframework. test.context.support.DependencyInjectionTestExecutionListener@57e603e6,org.springframework.test.context.support.DirtiesContextTestExecutionListener@3e0a1e1f]
这是目标片段
@Service
public class PipApps {
@Resource( name = …Run Code Online (Sandbox Code Playgroud) 我有一个带有2个Spring Boot应用程序的多模块Maven项目
亲
如何设置一个测试,您可以在同一个进程中加载单独的Spring引导应用程序,每个应用程序都有自己的配置上下文.
public abstract class AbstractIntegrationTest {//test module
protected FOO foo;
protected BAR bar;
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@IntegrationTest
@Transactional
@SpringApplicationConfiguration(classes = foo.Application.class)
public class FOO {
public MockMvc mockMvc;
@Autowired
public WebApplicationContext wac;
@Before
public void _0_setup() {
MockitoAnnotations.initMocks(this);
mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
TestCase.assertNotNull(mockMvc);
}
public void login(String username) {
}
}
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@IntegrationTest
@Transactional
@SpringApplicationConfiguration(classes = bar.Application.class)
public class BAR {
@Autowired
public WebApplicationContext wac;
public MockMvc restMvc;
@Before
public void _0_setup() {
MockitoAnnotations.initMocks(this);
restMvc …Run Code Online (Sandbox Code Playgroud) 我有一个春季启动应用程序.我正在写Junit测试.我试图从application.properties(在src/main/resources/application.properties中定义)和在AppConfig中配置的Status bean(src/main/java/hello/AppConfig.java)中注入值.我看到bean是自动装配的(通过调试器它不是null)但是没有设置值.
这是application.properties
src/main/resources/application.propertie s
app.name=rest-service
app.version=1.0.0-SNAPSHOT
Run Code Online (Sandbox Code Playgroud)
的src/main/JAVA /你好/ AppConfig.java
@Configuration
public class AppConfig {
@Value("${app.version}")
private String version;
@Value("${app.name}")
private String name;
@Bean
public Status status(){
return new Status(name,version);
}
}
Run Code Online (Sandbox Code Playgroud)
// Status是一个带名称和版本字段的简单pojo
SRC /测试/ JAVA /你好/ GreetingControllerTests.java
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Application.class)
@ContextConfiguration(classes={hello.TestConfig.class,hello.AppConfig.class})
@WebAppConfiguration
public class GreetingControllerTests {
@Autowired
Environment envi;
@Autowired
Status status;
@Value("${app.name:notConfigured}")
String appName;
private String env;
@Before
public void init(){
System.out.println(status.getName());
System.out.println(appName);
env=envi.getActiveProfiles()[0];
}
@Test
public void should_fail(){
if (env.equalsIgnoreCase("DEV")){
assertThat(false).isFalse();
}
if (env.equalsIgnoreCase("QA1")){
System.out.println("failing …Run Code Online (Sandbox Code Playgroud) 我正在使用Spring Boot 1.2.1.RELEASE,JUnit4和Gradle 2.1来获取RESTful服务,并且我正在尝试定义一个属性文件,该文件包含和/或覆盖将仅在JUnit测试中使用的值.当作为JUnit测试调用时,所有测试都会执行而不会出现问题.但是,当在gradle"build"或"test"任务期间运行这些相同的测试时,它们会失败,并出现"引发:java.lang.IllegalStateException:处于失败状态的Tomcat连接器",其根本原因为"java.net" .BindException:地址已在使用中:bind".
有多个测试类需要应用程序上下文才能运行.
为了通过属性文件来促进替代值,我已经包含了TestPropertySource()
是否需要额外的Gradle配置才能使其工作?
ControllerTest类
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@SpringApplicationConfiguration(classes = RESTAdapter.class)
@TestPropertySource(locations="classpath:application-junit.properties")
public class ControllerTest {
@Value("${test.token}")
private String token;
@Autowired
private WebApplicationContext wac;
private MockMvc mockMvc;
@Before
public void setup() {
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
}
public void TestMockMvc(String[] strings) throws Exception{
mockMvc.perform(URL_all_paramters, strings)
.param(Constants.PARAM_TOKEN, token)
.accept(Constants.APPLICATION_JSON_UTF8))
.andDo(print())
.andExpect(status().isOk())
.andExpect(content().contentType(Constants.APPLICATION_JSON_UTF8))
.andExpect(content().json(strings[strings.length-1]));
}
}
Run Code Online (Sandbox Code Playgroud)
application.properties(/ src/main/resources)
logging.level.org.springframework.web=TRACE
server.port=4040
shape.file=./shape/tl_2014_34_tabblock10_county_muni.shp
Run Code Online (Sandbox Code Playgroud)
application-junit.properties(/ src/test/resources)
test.token=..dDKidjwel
Run Code Online (Sandbox Code Playgroud)
的build.gradle
buildscript {
ext {
springBootVersion = '1.2.1.RELEASE'
}
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}") …Run Code Online (Sandbox Code Playgroud) junit4 gradle properties-file spring-boot springjunit4classrunner
我有一个spring boot项目,需要使用spring test runner进行测试(以便我可以获得真正的应用程序上下文)并模拟静态方法.
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes= MyApplication.class)
@PrepareForTest(StaticClass.class)
public class StaticClassTest {
@Rule
public PowerMockRule rule = new PowerMockRule();
@Autowired
HelloCmd hello;
@Test
public void testGetOne() {
mockStatic(StaticClass.class);
when(StaticClass.getNumber()).thenReturn(2);
System.out.println(hello.getNumber());
}
}
Run Code Online (Sandbox Code Playgroud)
运行测试时出现以下错误消息:
com.thoughtworks.xstream.converters.ConversionException: hello.hystrix.commands.HelloCmd$$EnhancerBySpringCGLIB$$a27be1be : hello.hystrix.commands.HelloCmd$$EnhancerBySpringCGLIB$$a27be1be
---- Debugging information ----
message : hello.hystrix.commands.HelloCmd$$EnhancerBySpringCGLIB$$a27be1be
cause-exception : com.thoughtworks.xstream.mapper.CannotResolveClassException
cause-message : hello.hystrix.commands.HelloCmd$$EnhancerBySpringCGLIB$$a27be1be
class : hello.hystrix.commands.StaticClassTest
required-type : hello.hystrix.commands.StaticClassTest
converter-type : com.thoughtworks.xstream.converters.reflection.ReflectionConverter
path : /org.powermock.modules.junit4.rule.PowerMockStatement$1/outer-class/fNext/next/next/target/hello
line number : 15
class[1] : org.junit.internal.runners.statements.InvokeMethod
class[2] : org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks
class[3] : org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks
class[4] : org.powermock.modules.junit4.rule.PowerMockStatement
class[5] : …Run Code Online (Sandbox Code Playgroud) 我用了两个单元测试类JUnit4.它们都可以单独运行,但是一个接一个地运行它们(例如通过mvn测试),第二个测试失败了.
第二次测试失败的原因是第一次测试在第一次测试中修改了一个bean.第二个测试想要使用这个bean的新实例.
单元测试应该为每个单元测试类提供一个新的Context.Spring对上下文缓存有一流的支持,我想禁用它.如何配置为每个单元测试类Spring重新启动新Context的?
我的测试类配置如下:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:a.context.xml")
public class AUnitTest {
@Test
public void someTestMethod{
doSomeFancyStuff();
}
}
Run Code Online (Sandbox Code Playgroud) java spring unit-testing spring-test springjunit4classrunner
spring ×5
spring-boot ×4
java ×2
junit4 ×2
spring-mvc ×2
spring-test ×2
unit-testing ×2
gradle ×1
junit ×1
maven ×1
powermock ×1
testing ×1