标签: spring-test

如何在静态@BeforeClass中自动装配字段?

@RunWith(SpringJUnit4ClassRunner.class)
public void ITest {
    @Autowired
    private EntityRepository dao;

    @BeforeClass
    public static void init() {
        dao.save(initialEntity); //not possible as field is not static
    }
}
Run Code Online (Sandbox Code Playgroud)

如何在静态init类中注入我的服务?

java junit spring spring-test

33
推荐指数
4
解决办法
1万
查看次数

在Integration测试中覆盖bean

对于我的Spring-Boot应用程序,我通过@Configuration文件提供了RestTemplate,因此我可以添加合理的默认值(ex Timeouts).对于我的集成测试,我想模拟RestTemplate,因为我不想连接到外部服务 - 我知道期望的响应.我尝试在集成测试包中提供不同的实现,希望后者将覆盖实际的实现,但是反过来检查日志:真正的实现覆盖了测试.

如何确保TestConfig中的那个是使用的?

这是我的配置文件:

@Configuration
public class RestTemplateProvider {

    private static final int DEFAULT_SERVICE_TIMEOUT = 5_000;

    @Bean
    public RestTemplate restTemplate(){
        return new RestTemplate(buildClientConfigurationFactory());
    }

    private ClientHttpRequestFactory buildClientConfigurationFactory() {
        HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
        factory.setReadTimeout(DEFAULT_SERVICE_TIMEOUT);
        factory.setConnectTimeout(DEFAULT_SERVICE_TIMEOUT);
        return factory;
    }
}
Run Code Online (Sandbox Code Playgroud)

整合测试:

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = TestConfiguration.class)
@WebAppConfiguration
@ActiveProfiles("it")
public abstract class IntegrationTest {}
Run Code Online (Sandbox Code Playgroud)

TestConfiguration类:

@Configuration
@Import({Application.class, MockRestTemplateConfiguration.class})
public class TestConfiguration {}
Run Code Online (Sandbox Code Playgroud)

最后是MockRestTemplateConfiguration

@Configuration
public class MockRestTemplateConfiguration {

    @Bean
    public RestTemplate restTemplate() {
        return Mockito.mock(RestTemplate.class)
    }
}
Run Code Online (Sandbox Code Playgroud)

java spring spring-test spring-boot spring-web

33
推荐指数
7
解决办法
4万
查看次数

使用Junit的Spring Test会话范围bean

我有一个会话范围的bean,它保存每个http会话的用户数据.我想编写一个Junit测试用例来测试会话范围的bean.我想编写测试用例,以便它可以证明每个会话都会创建bean.任何指针如何编写这样的Junit测试用例?

junit spring spring-mvc spring-test

32
推荐指数
3
解决办法
2万
查看次数

MockMvc 不再使用 Spring Boot 2.2.0.RELEASE 处理 UTF-8 字符

在升级到新发布2.2.0.RELEASE的 Spring Boot 版本后,我的一些测试失败了。看来,MediaType.APPLICATION_JSON_UTF8已弃用并且不再作为未明确指定内容类型的控制器方法的默认内容类型返回。

测试代码如

String content = mockMvc.perform(get("/some-api")
            .contentType(MediaType.APPLICATION_JSON))
            .andExpect(status().isOk())
            .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8))
            .andReturn()
            .getResponse()
            .getContentAsString();
Run Code Online (Sandbox Code Playgroud)

突然不再工作,因为内容类型不匹配,如下所示

java.lang.AssertionError: Content type 
Expected :application/json;charset=UTF-8
Actual   :application/json
Run Code Online (Sandbox Code Playgroud)

将代码更改为 .andExpect(content().contentType(MediaType.APPLICATION_JSON))暂时解决问题。

但是现在当与content预期的序列化对象进行比较时,如果对象中有任何特殊字符,仍然存在不匹配。似乎该.getContentAsString()方法默认不使用 UTF-8 字符编码(不再使用)。

java.lang.AssertionError: Response content expected:<[{"description":"Er hörte leise Schritte hinter sich."}]> but was:<[{"description":"Er hörte leise Schritte hinter sich."}]>
Expected :[{"description":"Er hörte leise Schritte hinter sich."}]
Actual   :[{"description":"Er hörte leise Schritte hinter sich."}]
Run Code Online (Sandbox Code Playgroud)

我怎样才能进入contentUTF-8 编码?

spring-mvc spring-test jackson spring-boot

31
推荐指数
4
解决办法
1万
查看次数

在春季测试中请求范围豆

我想在我的应用程序中使用请求范围的bean.我使用JUnit4进行测试.如果我尝试在这样的测试中创建一个:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:spring/TestScopedBeans-context.xml" })
public class TestScopedBeans {
    protected final static Logger logger = Logger
            .getLogger(TestScopedBeans.class);

    @Resource
    private Object tObj;

    @Test
    public void testBean() {
        logger.debug(tObj);
    }

    @Test
    public void testBean2() {
        logger.debug(tObj);
    }
Run Code Online (Sandbox Code Playgroud)

使用以下bean定义:

 <?xml version="1.0" encoding="UTF-8"?>
 <beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
  <bean class="java.lang.Object" id="tObj" scope="request" />
 </beans>           
Run Code Online (Sandbox Code Playgroud)

我得到:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'gov.nasa.arc.cx.sor.query.TestScopedBeans': Injection of resource fields failed; nested exception is java.lang.IllegalStateException: No Scope registered for scope 'request'
<...SNIP...>
Caused by: java.lang.IllegalStateException: No …
Run Code Online (Sandbox Code Playgroud)

java junit spring spring-mvc spring-test

28
推荐指数
4
解决办法
5万
查看次数

使用Mockito时如何在弹簧测试中清理模拟

我对Mockito很新,在清理方面遇到了一些麻烦.

我曾经使用JMock2进行单元测试.据我所知,JMock2在上下文中保留了期望和其他模拟信息,这些信息将针对每种测试方法进行重建.因此,每种测试方法都不会受到其他测试方法的干扰.

我在使用JMock2时采用了相同的弹簧测试策略,我发现我在帖子中使用的策略存在潜在问题:应用程序上下文是针对每个测试方法重建的,因此减慢了整个测试过程.

我注意到许多文章建议在春季测试中使用Mockito,我想尝试一下.它运行良好,直到我在测试用例中编写两个测试方法.每个测试方法在单独运行时通过,其中一个如果一起运行则失败.我推测这是因为模拟信息保存在模拟本身中(因为我没有在JMock中看到任何类似的上下文对象)并且模拟(和应用程序上下文)在两个测试方法中共享.

我通过在@Before方法中添加reset()来解决它.我的问题是处理这种情况的最佳做法是什么(reset()的javadoc说如果你需要reset(),代码就闻到了?)?任何想法都是欣赏,提前谢谢.

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {
    "file:src/main/webapp/WEB-INF/booking-servlet.xml",
    "classpath:test-booking-servlet.xml" })
@WebAppConfiguration
public class PlaceOrderControllerIntegrationTests implements IntegrationTests {

@Autowired
private WebApplicationContext wac;

private MockMvc mockMvc;

@Autowired
private PlaceOrderService placeOrderService;

@Before
public void setup() {
    this.mockMvc = webAppContextSetup(this.wac).build();

    reset(placeOrderService);// reset mock
}

@Test
public void fowardsToFoodSelectionViewAfterPendingOrderIsPlaced()
        throws Exception {

    final Address deliveryAddress = new AddressFixture().build();
    final String deliveryTime = twoHoursLater();
    final PendingOrder pendingOrder = new PendingOrderFixture()
            .with(deliveryAddress).at(with(deliveryTime)).build();

    when(placeOrderService.placeOrder(deliveryAddress, with(deliveryTime)))
            .thenReturn(pendingOrder);

    mockMvc.perform(...);

}

@Test
public void returnsToPlaceOrderViewWhenFailsToPlaceOrder() throws Exception …
Run Code Online (Sandbox Code Playgroud)

spring-mvc spring-test mockito

26
推荐指数
5
解决办法
4万
查看次数

Spring boot 1.4测试:配置错误:找到了@BootstrapWith的多个声明

按照官方文档:http: //docs.spring.io/spring-boot/docs/1.4.0.M2/reference/htmlsingle/#Testing

我想测试一个我的REST API方法,如下所示:

@RunWith(SpringRunner.class)
@WebMvcTest(LoginController.class)
@SpringBootTest(classes = Application.class)
public class AuthorizationServiceTest {
    @Autowired
    private TestRestTemplate restTemplate;

    @Test
    public void test() {
        Object returnedObject=his.restTemplate.getForObject("/login", Object.class);
    }
}
Run Code Online (Sandbox Code Playgroud)

正如文件中所述:

搜索算法从包含测试的包开始工作,直到找到@SpringBootApplication或@SpringBootConfiguration注释类.只要您以合理的方式构建代码,通常就会找到主要配置.

我已正确构建了我的代码(至少我认为):

AuthorizationService:在包com.xxx.yyy.zzz.authorization下;

AuthorizationServiceTest:在包com.xxx.yyy.zzz.authorizationTest下;

我收到此异常(完整跟踪):

java.lang.IllegalStateException: Configuration error: found multiple declarations of @BootstrapWith for test class [com.orangeraid.rasberry.gateway.authorizationTest.AuthorizationServiceTest]: [@org.springframework.test.context.BootstrapWith(value=class org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTestContextBootstrapper), @org.springframework.test.context.BootstrapWith(value=class org.springframework.boot.test.context.SpringBootTestContextBootstrapper)]
    at org.springframework.test.context.BootstrapUtils.resolveExplicitTestContextBootstrapper(BootstrapUtils.java:155)
    at org.springframework.test.context.BootstrapUtils.resolveTestContextBootstrapper(BootstrapUtils.java:126)
    at org.springframework.test.context.TestContextManager.<init>(TestContextManager.java:105)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTestContextManager(SpringJUnit4ClassRunner.java:152)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.<init>(SpringJUnit4ClassRunner.java:143)
    at org.springframework.test.context.junit4.SpringRunner.<init>(SpringRunner.java:49)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:422)
    at org.junit.internal.builders.AnnotatedBuilder.buildRunner(AnnotatedBuilder.java:104)
    at org.junit.internal.builders.AnnotatedBuilder.runnerForClass(AnnotatedBuilder.java:86)
    at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:59) …
Run Code Online (Sandbox Code Playgroud)

java spring spring-mvc spring-test spring-boot

23
推荐指数
4
解决办法
2万
查看次数

无法加载TestContextBootstrapper - Spring Unit测试

我必须使用Spring在我的一个Dao类上执行单元测试.这是我的单元测试:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath:app-config.xml"})
@ActiveProfiles("local")
public class HouseDaoTest {

    @Autowired
    HouseDataDao houseDataDao;

    @Test
    public void saveTest(){
        HouseData data = new HouseData();
        Address add = new Address();
        // Truncating for sake of simplicity
        houseDataDao.save(data);
    }
}
Run Code Online (Sandbox Code Playgroud)

和我的bean配置文件:

APP-config.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"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    <import resource="BeanConfiguration-localhost.xml"/>
    <import resource="BeanConfiguration-production.xml"/>
</beans>
Run Code Online (Sandbox Code Playgroud)

BeanConfiguration-localhost.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans profile="local" 
    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:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
    <context:annotation-config />
    <tx:annotation-driven />
    <bean id="dataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://localhost:3306/dbtest" /> …
Run Code Online (Sandbox Code Playgroud)

spring unit-testing spring-test

22
推荐指数
2
解决办法
3万
查看次数

Spring Boot:@TestConfiguration在集成测试期间不覆盖Bean

Bean在用@Configuration修饰的类中定义了:

@Configuration
public class MyBeanConfig {

    @Bean
    public String configPath() {
        return "../production/environment/path";
    }
}
Run Code Online (Sandbox Code Playgroud)

我有一个用@TestConfiguration修饰的类应该覆盖它Bean:

@TestConfiguration
public class MyTestConfiguration {

    @Bean
    @Primary
    public String configPath() {
        return "/test/environment/path";
    }
}
Run Code Online (Sandbox Code Playgroud)

configPathbean用于设置外部文件的路径,该文件包含必须在启动期间读取的注册码.它用在@Component类中:

@Component
public class MyParsingComponent {

    private String CONFIG_PATH;

    @Autowired
    public void setCONFIG_PATH(String configPath) {
        this.CONFIG_PATH = configPath;
    }
}
Run Code Online (Sandbox Code Playgroud)

在尝试调试时,我在每个方法中设置了一个断点以及测试配置类的构造函数.在@TestConfiguration类的构造函数断点命中,所以我知道我的测试配置类实例化,但是configPath()该类的方法不会被击中.相反,configPath()正常的@Configuration类的方法被命中,而@Autowired Stringin MyParsingComponent总是../production/environment/path而不是预期的/test/environment/path.

不知道为什么会这样.任何想法将不胜感激.

java spring-test spring-boot

22
推荐指数
6
解决办法
2万
查看次数

当使用maven-surefire运行测试时,在@BeforeClass之后发生Spring-Autowiring

我在依赖注入(Spring autowiring)和maven-surefire方面遇到了一些问题.使用TestNG在eclipse中运行时,以下测试没有问题:注入service-object,然后@BeforeClass调用-method.

@TransactionConfiguration(defaultRollback=false)
@ContextConfiguration(locations={"/testContext.xml"})
public class MyServiceTest extends AbstractTransactionalTestNGSpringContextTests {


@Autowired
private MyService service;

@BeforeTest
public void setup() {
    System.out.println("*********************"+service);
    Assert.assertNotNull(service);
}
Run Code Online (Sandbox Code Playgroud)

但是,当我使用maven-surefire运行相同的测试用例时,首先调用setup(),这会导致测试失败:

[INFO] --- maven-surefire-plugin:2.7.2:test (default-test) @ myserver ---
[INFO] Surefire report directory: D:\...
-------------------------------------------------------
 T E S T S
-------------------------------------------------------
Running TestSuite
**************************null
2011-03-04 11:08:57,462 DEBUG  ionTestExecutionListener.prepareTestInstance  - Performing dependency injection for test context [[TestContext@1fd6bea...
2011-03-04 11:08:57,462 DEBUG  ractGenericContextLoader.loadContext          - Loading ApplicationContext for locations [classpath:/testContext.xml].
Run Code Online (Sandbox Code Playgroud)

我怎么解决这个问题?如果我更换@BeforeClass@Test它在行家的作品作为TestNG的Eclipse插件.

Maven的万无一失,插件:2.7.2

Eclipse:Helios Service Release 1

jdk1.6.0_14 …

java testng spring spring-test maven

21
推荐指数
3
解决办法
1万
查看次数