Java 使用Spring自动连接时创建bean
我正在尝试为我的控制器编写一个测试。当web服务运行时,一切正常。但是,当我运行测试时,我得到:Java 使用Spring自动连接时创建bean,java,spring,spring-mvc,dependency-injection,autowired,Java,Spring,Spring Mvc,Dependency Injection,Autowired,我正在尝试为我的控制器编写一个测试。当web服务运行时,一切正常。但是,当我运行测试时,我得到: 创建名为“Controller”的bean时出错:通过字段“service”表示未满足的依赖关系;嵌套异常为org.springframework.beans.factory.NoSuchBeanDefinitionException:没有“com.prov.Service”类型的合格bean可用:至少需要1个符合autowire候选条件的bean。依赖项注释:{@org.springframewo
创建名为“Controller”的bean时出错:通过字段“service”表示未满足的依赖关系;嵌套异常为org.springframework.beans.factory.NoSuchBeanDefinitionException:没有“com.prov.Service”类型的合格bean可用:至少需要1个符合autowire候选条件的bean。依赖项注释:{@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);
}
}
控制器类自动连接服务类。因此,测试控制器类需要服务类的存在,因为控制器依赖于创建服务类型的bean。这意味着您必须将服务类
@自动连接到测试中,或者(最好)使用类似的方式模拟它
(使用代码示例编辑):
请注意,此示例使用Hamcrest来模拟is()
和equalTo()
谢谢,我以前曾尝试使用@MockBean
模拟该服务,但我没有使用Mockito
来模拟对该服务的实际调用。我的最后一个方法与您提供的方法之间的唯一区别是,我的参数和负载是自定义类对象,我不使用最后一行:.andExpect(jsonPath($),is(equalTo(“Hello,World”)因为我只需要显示端点是可访问的。我添加这些只是为了演示如何可能检查控制器返回的值。很乐意帮忙!
@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();
}
}
}
@RunWith(SpringRunner.class)
@WebMvcTest(Controller.class)
public class ControllerTest {
@MockBean
private Service service
@Autowired
private MockMvc mvc;
@Test
public void foo() {
String somePayload = "Hello, World";
String myParams = "foo";
when(service.method(myParams)).thenReturn(somePayload);
mvc.perform(get("my/url/to/test").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(jsonPath("$", is(equalTo("Hello, World"))));
}
}