我正在爲我的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 –