开发者社区 问答 正文

springboot @WebMvcTest测试controller报No qu?报错

spring boot版本1.4.0

JDK1.8

代码如下:

package com.qq.spring.boot.dao;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

@Repository
public class BookDao {

	@Autowired
	private JdbcTemplate jdbcTemplate;
	
	public Integer addBook(String name){
		String sql = "insert into books (bname)values('"+name+"')";
		return jdbcTemplate.update(sql);
	}
}



package com.qq.spring.boot.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import com.qq.spring.boot.dao.BookDao;

@RestController
public class BookController {

	@Autowired
	private BookDao bookDao;
	
	@GetMapping("/book/home")
	public String home(){
		System.out.println("xxxxxxxxxxxxxhomexxxxxxxxxx");
		bookDao.addBook("home");
		return "bookhome";
	}
}



test代码如下:

package com.qq.spring.boot.controller;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;

@RunWith(SpringRunner.class)
@WebMvcTest(controllers = BookController.class)
public class BookControllerTest {

	 @Autowired
	 private MockMvc mvc;
	 
	@Test
	public void testHome() throws Exception {
		mvc.perform(MockMvcRequestBuilders.get("/book/home"))
        .andExpect(MockMvcResultMatchers.status().isOk()).andExpect(MockMvcResultMatchers.content().string("bookhome"));
	}
}



现在的问题是这样的,正常跑,可以访问/book/home url,没有问题
但是,跑junit test的时候,报错,
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.qq.spring.boot.dao.BookDao] found for dependency [com.qq.spring.boot.dao.BookDao]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

我的spring容器中,是有BookDao这个bean的,为啥还是报错?













展开
收起
爱吃鱼的程序员 2020-06-09 10:46:42 860 分享 版权
1 条回答
写回答
取消 提交回答
  • https://developer.aliyun.com/profile/5yerqm5bn5yqg?spm=a2c6h.12873639.0.0.6eae304abcjaIB

    MockMvcmvc 不会加整个spring框架的回复<aclass='referer'target='_blank'>@李三石:好的。非常感谢,感谢提醒回复<aclass='referer'target='_blank'>@西夏一品堂:你有两个选择,用MockMvc只测试controller层代码,其他的都使用mock方式提供或者使用@RunWith(SpringJUnit4ClassRunner.class)加载整个spring框架进行测试怎么解决?

    2020-06-09 10:46:58
    赞同 展开评论