Spring JUnit:如何在自动装配组件中模拟自动装配组件

新手上路,请多包涵

我有一个我想测试的 Spring 组件,这个组件有一个 autowired 属性,我需要更改它以进行单元测试。问题是,该类在构造后方法中使用了自动装配组件,因此我无法在实际使用之前替换它(即通过 ReflectionTestUtils)。

我该怎么做?

这是我要测试的课程:

 @Component
public final class TestedClass{

    @Autowired
    private Resource resource;

    @PostConstruct
    private void init(){
        //I need this to return different result
        resource.getSomething();
    }
}

这是测试用例的基础:

 @RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations= "classpath:applicationContext.xml")
public class TestedClassTest{

    @Autowired
    private TestedClass instance;

    @Before
    private void setUp(){
        //this doesn't work because it's executed after the bean is instantiated
        ReflectionTestUtils.setField(instance, "resource", new Resource("something"));
    }
}

在调用 postconstruct 方法之前,有没有办法用其他东西替换资源?想告诉 Spring JUnit runner 自动装配不同的实例吗?

原文由 NeplatnyUdaj 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 690
2 个回答

您可以提供一个新的 testContext.xml,其中您定义的 @Autowired bean 是您测试所需的类型。

原文由 phury 发布,翻译遵循 CC BY-SA 3.0 许可协议

你可以使用 Mockito 。我不确定 PostConstruct 具体来说,但这通常有效:

 // Create a mock of Resource to change its behaviour for testing
@Mock
private Resource resource;

// Testing instance, mocked `resource` should be injected here
@InjectMocks
@Resource
private TestedClass testedClass;

@Before
public void setUp() throws Exception {
    // Initialize mocks created above
    MockitoAnnotations.initMocks(this);
    // Change behaviour of `resource`
    when(resource.getSomething()).thenReturn("Foo");
}

原文由 Anna Zubenko 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题