我正在为我的Spring启动项目中的以下类写一个端到端测试,但我收到org.springframework.beans.factory.NoSuchBeanDefinitionException
错误,因为No qualifying bean of type 'com.boot.cut_costs.service.CustomUserDetailsService' available
。春季启动jUnit测试失败,因为“org.springframework.beans.factory.NoSuchBeanDefinitionException”
@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个
我的春天启动的应用程序入口点是App.java
:
@SpringBootApplication
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
}
我认为原因也是背景。试试这个: @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = {“location/to/test-config.xml”}) –
什么是“位置”?它指向什么? –
请参考:http://docs.spring.io/spring/docs/3.0.x/spring-framework-reference/html/resources.html#resources-app-ctx –