使用Spring自动装配时创建bean

时间:2017-07-05 23:59:17

标签: java spring spring-mvc dependency-injection autowired

我正在尝试为我的控制器编写测试。当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();
        }
    }

}

1 个答案:

答案 0 :(得分:1)

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()

之类的内容
相关问题