【发布时间】:2017-07-05 23:59:17
【问题描述】:
我正在尝试为我的控制器编写测试。当 Web 服务运行时,一切正常。但是,当我运行测试时,我得到:
Error creating bean with name 'Controller': Unsatisfied dependency expressed through field 'service'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.prov.Service' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
正如您在下面看到的,我相信所有内容都已正确自动装配,并且我的项目结构已正确设置,因此组件扫描仪可以正确找到注释,但我仍然收到此错误。
控制器:
@RestController
@RequestMapping("/api")
public class Controller {
@Autowired
private Service service;
@JsonView(Views.All.class)
@RequestMapping(value = "/prov/users", method = RequestMethod.POST)
@ResponseBody
public CommonWebResponse<String> handleRequest(@RequestBody UserData userData) {
return service.prov(userData);
}
}
服务:
@Service
public class Service {
@Autowired
private Repo repo;
@Autowired
private OtherService otherService;
public CommonWebResponse<String> prov(UserData userData) {
// do stuff here
return new SuccessWebResponse<>("Status");
}
}
控制器测试:
@RunWith(SpringRunner.class)
@WebMvcTest(
controllers = Controller.class,
excludeFilters = {
@ComponentScan.Filter(
type = FilterType.ASSIGNABLE_TYPE,
value = {CorsFilter.class, AuthenticationFilter.class}
)
}
)
@AutoConfigureMockMvc(secure = false)
public class ControllerTest {
public static final MediaType APPLICATION_JSON_UTF8 = new MediaType(MediaType.APPLICATION_JSON.getType(), MediaType.APPLICATION_JSON.getSubtype(), Charset.forName("utf8"));
@Autowired
private MockMvc mvc;
@Test
public void connectToEndpoint_shouldReturnTrue() {
UserData userData = new UserData("a", "bunch", "of", "fields");
try {
mvc.perform(post("/api/prov/users").contentType(APPLICATION_JSON_UTF8)
.content(asJsonString(userData))
.accept(MediaType.ALL))
.andExpect(status().isOk());
} catch (Exception e) {
Assert.fail();
}
}
}
【问题讨论】:
标签: java spring spring-mvc dependency-injection autowired