【问题标题】:inject bean with real parameters with mockito使用 mockito 注入具有真实参数的 bean
【发布时间】:2018-10-11 08:47:37
【问题描述】:

我正在尝试使用 mockito 编写一个单元测试用例,我想注入一个带有真实参数而不是模拟参数的 bean。

该 bean 有一些从 .properties 文件中读取的字符串值。

@Component
public class SomeParameters {

    @Value("${use.queue}")
    private String useQueue;

 }

@RunWith(MockitoJUnitRunner.class)
public class ServiceTest {

    @Mock
    private A a;

    @Autowired
    private SomeParameters someParameters;

    @Before
    public void init() {
        MockitoAnnotations.initMocks(this);

    }

    @Test
    public void testMethod() {
        if(someParameters.getUseQueue==true){
            //do something
        }else{
            /bla bla
        }
    }

我的主要目标是运行具有真实场景的测试用例。我不想使用模拟值。

我能够以这种方式注入带有真实参数的 bean。但这是单元测试用例,而不是集成测试。所以我不应该给applicationContext。你能指导我如何处理这种情况吗?

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:applicationContextTest.xml"})
public class ServiceTest {

【问题讨论】:

    标签: java spring unit-testing mockito spring-test


    【解决方案1】:

    如果你想使用 spring-context 那么你应该为你的测试创建一个配置(通过 xml 或 java 配置)并且只声明你需要的 bean。 For Example

    对于设置属性只需声明@TestPropertiesSource("use.queue=someValue") 否则您需要从测试资源中读取值。

    PS。还要检查@MockBean and @SpyBean,尤其是@SpyBean

    【讨论】:

    • 我想我会使用 spring-context。没有弹簧上下文就无法使用 bean(未模拟)。谢谢
    【解决方案2】:

    如果要使用真实属性,则使用 Properties 对象加载属性文件并通过从 Properties 对象获取值来模拟值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-11-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-01
      • 2016-11-26
      • 1970-01-01
      相关资源
      最近更新 更多