[英]Creating beans when Autowiring with Spring
I am trying to write a test for my controller. 我正在尝试为我的控制器编写测试。 When the web service is running everything works fine.
当Web服务运行时,一切正常。 However, when I run the test I get:
但是,当我运行测试时,我得到:
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)}
As you can see below, I believe have everything correctly Autowired and my project structure is correctly set up so that the component scanner can find the annotations properly, yet I still get this error. 正如您在下面看到的,我相信所有东西都可以正确自动布线,并且我的项目结构正确设置,以便组件扫描程序可以正确找到批注,但是仍然出现此错误。
Controller: 控制器:
@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: 服务:
@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");
}
}
Controller Test: 控制器测试:
@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();
}
}
}
The Controller class autowires your Service class. Controller类自动为Service类布线。 Therefore, testing the Controller class requires existence of your Service class because Controller depends on creating a bean of type Service.
因此,测试Controller类需要您的Service类存在,因为Controller依赖于创建Service类型的Bean。 This means you either have to
@Autowired
your service class into your test, or (preferably) mock it using something like Mockito . 这意味着您必须将服务类
@Autowired
插入测试中,或者(最好)使用Mockito之类的东西对其进行模拟。
(edit with code example): (使用代码示例进行编辑):
@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"))));
}
}
Do note that this example uses Hamcrest for things like is()
and equalTo()
请注意,此示例将Hamcrest用于
is()
和equalTo()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.