Spring 3自动布线和junit测试 [英] spring 3 autowiring and junit testing

查看:70
本文介绍了Spring 3自动布线和junit测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码:

@Component
public class A {
    @Autowired
    private B b;

    public void method() {}
}

public interface X {...}

@Component
public class B implements X {
    ...
}

我想在隔离类A中进行测试.我是否必须模拟B类?如果是,怎么办?因为它是自动连线的,所以没有可以在其中发送模拟对象的设置器.

I want to test in isolation class A. Do I have to mock class B? If yes, how? Because it is autowired and there is no setter where i could send the mocked object.

推荐答案

我想在隔离类A中进行测试.

I want to test in isolation class A.

您应该完全模拟B,而不是实例化并注入B的实例.关键是测试A是否B有效,因此,您不应让可能损坏的B干扰A的测试.

You should absolutely mock B, rather than instantiate and inject an instance of B. The point is to test A whether or not B works, so you should not allow a potentially broken B interfere with the testing of A.

也就是说,我强烈推荐 Mockito .随着模拟框架的发展,它非常易于使用.您将编写如下内容:

That said, I highly recommend Mockito. As mocking frameworks go, it is extremely easy to use. You would write something like the following:

@Test
public void testA() {
    A a = new A();
    B b = Mockito.mock(B.class); // create a mock of B
    Mockito.when(b.getMeaningOfLife()).thenReturn(42); // define mocked behavior of b
    ReflectionTestUtils.setField(a, "b", b); // inject b into the B attribute of A

    a.method();

    // call whatever asserts you need here
}

这篇关于Spring 3自动布线和junit测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆