【问题标题】:Injecting only some properties, mocking others只注入一些属性,嘲笑其他的
【发布时间】:2014-11-09 11:04:39
【问题描述】:

我正在为一个 Bean 编写单元测试,该 Bean 有一些使用 spring 自动装配的属性。

这是豆子:

public class Goober {

     @Autowired
     private ObjectX prop1;

     @Autowired
     private ObjectY prop2;


     //... rest of object
}

在我的单元测试中,我想使用 jmockit 模拟 prop1,但通过 spring 注入 prop2。这是我的测试的样子:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "/applicationContext-test.xml" })
public class GooberUT extends TestCase{

    @Tested @Autowired
    Goober goober;

    @Test
    public void gooberTest (@Injectable prop1) {


        // .. test and whatnot here
    }


    // .. setup/teardown etc
}

这里的问题是 prop1 将由 spring 自动装配。如果我从测试中删除 @Autowired 注释,那么 prop1 将被模拟,但 prop2 将为空。

如何使用 jMockit 在 Goober 中注入一个属性,并自动装配另一个?

【问题讨论】:

    标签: java spring unit-testing junit jmockit


    【解决方案1】:

    如果ObjectY是一个类而不是一个接口,你可以有如下的测试类:

    public class GooberUT
    {
        @Tested(fullyInitialized = true)
        Goober goober;
    
        @Test
        public void gooberTest(@Injectable ObjectX prop1)
        {
            // .. test and whatnot here
        }
    
        // .. setup/teardown etc
    }
    

    使用@Tested(fullyInitialized = true),JMockit 将递归地实例化并注入测试对象中的所有字段。但是,匹配 @Injectable 的字段将接收模拟实例。

    【讨论】:

      【解决方案2】:

      您可以让 Spring 注入 prop1,然后使用 ReflectionTestUtils 的 setProperty 方法覆盖 prop1 的值,并以编程方式注入您喜欢的任何内容。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-11-10
        • 2014-10-27
        • 2011-04-10
        • 1970-01-01
        • 2016-10-02
        • 2019-12-20
        • 1970-01-01
        • 2019-02-15
        相关资源
        最近更新 更多