gpt4 book ai didi

java - Spring boot jUnit 测试失败,因为 "org.springframework.beans.factory.NoSuchBeanDefinitionException"

转载 作者:行者123 更新时间:2023-11-30 02:27:49 24 4
gpt4 key购买 nike

我正在为 Spring boot 项目中的以下类编写端到端测试,但收到 org.springframework.beans.factory.NoSuchBeanDefinitionException 错误,因为 No Qualifying类型为“com.boot.cut_costs.service.CustomUserDetailsS​​ervice”的 bean 可用

@RestController
public class AuthenticationController {

@Autowired
protected AuthenticationManager authenticationManager;
@Autowired
private CustomUserDetailsService userDetailsServices;
@Autowired
private UserDetailsDtoValidator createUserDetailsDtoValidator;

@RequestMapping(value = "/signup", method = RequestMethod.POST)
public void create(@RequestBody UserDetailsDto userDetailsDTO, HttpServletResponse response, BindingResult result) {
// ...
userDetailsServices.saveIfNotExists(username, password, name);
// ...
if (authenticatedUser != null) {
AuthenticationService.addAuthentication(response, authenticatedUser.getName());
SecurityContextHolder.getContext().setAuthentication(authenticatedUser);
} else {
throw new BadCredentialsException("Bad credentials provided");
}
}
}

测试类:

@RunWith(SpringRunner.class)
@WebMvcTest(AuthenticationController.class)
public class AuthenticationControllerFTest {

@Autowired
private MockMvc mockMvc;

@MockBean
private AuthenticationManager authenticationManager;

@Test
public void testCreate() throws Exception {
Authentication authentication = Mockito.mock(Authentication.class);
Mockito.when(authentication.getName()).thenReturn("DUMMY_USERNAME");
Mockito.when(
authenticationManager.authenticate(Mockito
.any(UsernamePasswordAuthenticationToken.class)))
.thenReturn(authentication);

//....
RequestBuilder requestBuilder = MockMvcRequestBuilders
.post("/signup")
.accept(MediaType.APPLICATION_JSON).content(exampleUserInfo)
.contentType(MediaType.APPLICATION_JSON);

MvcResult result = mockMvc.perform(requestBuilder).andReturn();

MockHttpServletResponse response = result.getResponse();
}
}

我认为发生此错误是因为在测试环境中,spring 上下文的加载方式与开发/生产环境中的加载方式不同。我应该如何解决这个问题?

编辑 1

我的 Spring boot 应用程序入口点是 App.java:

@SpringBootApplication
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
}

最佳答案

@WebMvcTest 仅加载 Controller 配置。这就是为什么你有这个 DI 错误(有了它,你必须为你的服务提供模拟)。因此,如果您需要注入(inject)服务,可以使用@SpringBootTest

如果您使用@SpringBootTest,则还必须使用@AutoConfigureMockMvc来配置MockMvc

关于java - Spring boot jUnit 测试失败,因为 "org.springframework.beans.factory.NoSuchBeanDefinitionException",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45184882/

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