[英]Creating beans when Autowiring with Spring
我正在嘗試為我的控制器編寫測試。 當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();
}
}
}
Controller類自動為Service類布線。 因此,測試Controller類需要您的Service類存在,因為Controller依賴於創建Service類型的Bean。 這意味着您必須將服務類@Autowired
插入測試中,或者(最好)使用Mockito之類的東西對其進行模擬。
(使用代碼示例進行編輯):
@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"))));
}
}
請注意,此示例將Hamcrest用於is()
和equalTo()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.