繁体   English   中英

使用Spring自动装配时创建bean

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM