gpt4 book ai didi

java - Spring JUnit : How to Mock autowired component in autowired component

转载 作者:IT老高 更新时间:2023-10-28 13:02:41 28 4
gpt4 key购买 nike

我有一个我想测试的 Spring 组件,并且这个组件有一个 Autowiring 的属性,我需要更改它以进行单元测试。问题是,该类在 post-construct 方法中使用 Autowiring 组件,因此在实际使用之前我无法替换它(即通过 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 Autowiring 不同的实例?

最佳答案

您可以使用 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");
}

关于java - Spring JUnit : How to Mock autowired component in autowired component,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19299513/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com