Junit单元测试中获得spring bean

4 篇文章 0 订阅

主要介绍单元测试中获得bean的三种方法,以及各自的优劣。其实跟开发时获得bean方法一样,如下:

a.通过ClassPathXmlApplicationContext得到ApplicationContext,再getBean

b.通过set函数获得bean

c.启用直接对保护类型属性变量进行注入的机制

日常应用中推荐大家使用第二、三中方法。尤其对于bean较多时,使用第三种可以方便省事很多。

 

所用依赖为junit 3.8.1和spring-test包2.5.6。下面为详细介绍:

 

1、通过ClassPathXmlApplicationContext得到ApplicationContext,再getBean

单元测试中需要引入bean,最容易想到的办法就是使用spring bean注入的原理,代码如下:

package com..*.*.*.test;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.test.AbstractDependencyInjectionSpringContextTests;

import com.*.*.*.TestService;

public class TestBean extends AbstractDependencyInjectionSpringContextTests {

    @Test
    public void testBeanInjection() {
         ApplicationContext testContext = new ClassPathXmlApplicationContext("test_services.xml");
         TestService testService = (TestService)testContext.getBean("testService");
    }
}

先通过ClassPathXmlApplicationContext bean xml得到ApplicationContext,再getBean。

但按照Spring的推荐,在单元测试时不应该依赖于Spring容器,也就是说不应该在单元测试时启动ApplicationContext并从中获取Bean,所以此种方法不推荐。建议大家继续看看下面两种

其中test_services.xml内容如下,下面两种方法一样。

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans default-autowire="byName">
	<bean id="testService"
		class="com.*.*.*.TestServiceImpl">
	</bean>
</beans>

 

2、通过set函数获得bean

通过getConfigLocations设置bean xml路径

新增setTestService设置函数,对testService赋值

注意testService的类型不限制

package com..*.*.*.test;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.test.AbstractDependencyInjectionSpringContextTests;

import com.*.*.*.TestService;

public class TestSendEmail extends AbstractDependencyInjectionSpringContextTests {

    private TestService testService;

    public void setTestService(TestService testService) {
        this.testService = testService;
    }

    /**
     * 设置bean xml路径,可以添加多个
     */
    protected String[] getConfigLocations() {
        return new String[] {"test_services.xml"};
    }

    @Test
    public void testBeanInjection() {
        assertTrue(testService != null);
    }
}

这种方式的好处在不用手动加载bean xml文件,但每个bean需要一个set函数,当bean较多时需要生成较多set函数

 

 

3、启用直接对保护类型属性变量进行注入的机制

通过getConfigLocations设置bean xml路径

新增构造函数,在其中调用setPopulateProtectedVariables(true)设置启用直接对保护类型属性变量进行注入的机制

注意testService为保护型

package com..*.*.*.test;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.test.AbstractDependencyInjectionSpringContextTests;

import com.*.*.*.TestService;

public class TestBean extends AbstractDependencyInjectionSpringContextTests {

    protected TestService testService;

    public TestBean(){
        // 启用直接对保护类型属性变量进行注入的机制
        this.setPopulateProtectedVariables(true);
    }

	/**
     * 设置bean xml路径,可以添加多个
     */
    protected String[] getConfigLocations() {
        return new String[] {"test_services.xml"};
    }

    @Test
    public void testBeanInjection() {
        assertTrue(testService != null);
    }
}

这种方式的好处在不用手动加载bean xml文件,也不用再写set函数 ,但需要一个构造函数并在其中启用直接对保护类型属性变量进行注入的机制

 

其他:

程序中依赖了spring-test的包,需要在pom中添加依赖如下

<dependency>
	<groupId>org.springframework</groupId>
	<artifactId>spring-test</artifactId>
	<version>2.5.6</version>
</dependency>

 参考:http://mvnrepository.com/artifact/org.springframework/spring-test/2.5

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot的JUnit单元测试,可以使用Mockito来创建mock数据,Mockito是一个流行的Java测试框架,可以模拟对象的行为和方法,以便更容易地测试代码。 下面是一个简单的示例,演示如何在Spring Boot的JUnit测试使用Mockito创建mock数据: 假设有一个UserService类,其有一个getUserById()方法,可以通过用户ID获取用户对象。 ```java @Service public class UserService { @Autowired private UserRepository userRepository; public User getUserById(Long id) { return userRepository.findById(id); } } ``` 现在我们想测试getUserById()方法,但是我们不想依赖于实际的数据库和UserRepository对象,而是想使用mock数据来测试它。我们可以使用Mockito来创建mock UserRepository对象,并在测试使用它。 ```java @RunWith(SpringRunner.class) @SpringBootTest public class UserServiceTest { @Autowired private UserService userService; @MockBean private UserRepository userRepository; @Test public void testGetUserById() { User user = new User(); user.setId(1L); user.setName("Alice"); Mockito.when(userRepository.findById(1L)).thenReturn(user); User result = userService.getUserById(1L); Assert.assertEquals("Alice", result.getName()); } } ``` 在这个示例,我们使用@MockBean注解创建了一个mock的UserRepository对象,并使用Mockito.when()方法来告诉Mockito当findById()方法被调用时应该返回什么对象。 然后,我们调用UserService的getUserById()方法,它将使用我们创建的mock对象而不是实际的数据库和UserRepository对象。 最后,我们使用JUnit的Assert.assertEquals()方法来验证getUserById()方法返回的用户对象是否符合预期。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值