gpt4 book ai didi

java - 单元测试中的@Autowire 似乎不起作用

转载 作者:行者123 更新时间:2023-11-29 06:52:38 24 4
gpt4 key购买 nike

我有一个使用 Mockito 和 Spring 4 的单元测试设置。我的测试如下所示:

@ContextConfiguration(classes = {
MyTestConfig.class,
SecurityConfig.class,
OAuth2Config.class
})
@RunWith(MockitoJUnitRunner.class)
public class ControllerAccessTests {

private MockMvc mockMvc;

@Autowired
private FilterChainProxy springSecurityFilterChain;

@Mock
private CreditCardPaymentService creditCardPaymentService;
@InjectMocks
private CreditCardRestController creditCardRestController;

@Before
public void setUp() throws Exception {
mockMvc = MockMvcBuilders
.standaloneSetup(creditCardRestController)
.apply(springSecurity(springSecurityFilterChain))
.build();
when(creditCardPaymentService.doPreAuthPayment(any())).thenReturn(null);
}

@Test
//.... some unit tests

使用如下所示的配置文件:

@Configuration
public class MyTestConfig {

@Bean
public FilterChainProxy springSecurityFilterChain(){
AntPathRequestMatcher matcher = new AntPathRequestMatcher("/**");
DefaultSecurityFilterChain chain = new DefaultSecurityFilterChain(matcher);
return new FilterChainProxy(chain);
}

}

当我开始单元测试时 springSecurityFilterChain 是空的,所以看起来配置文件 MyTestConfig 似乎没有被加载。有任何想法吗?

干杯汤姆

最佳答案

如果你想使用 mockito 注释和 spring 注入(inject),那么:

1) 使用@RunWith(SpringJUnit4ClassRunner.class)

2) 创建一个初始化方法:

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

关于java - 单元测试中的@Autowire 似乎不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42507310/

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