Autowire 在 Spring 测试中不起作用

Jam*_*nux 1 testing spring autowired

我创建了一个简单的 RestController,它自动连接 EntityManager 和我拥有的其他类。如果我运行我的应用程序,一切正常,自动装配被定义。现在我尝试为我的班级创建一个简单的测试:

@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@EnableWebMvc
@ContextConfiguration(classes = MonitoringController.class)
public class MonitoringControllerTest {

    private MockMvc mockMvc;

    @Autowired
    WebApplicationContext wac;

    @Before
    public void setup() {mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();

    }

    @Test
    public void testMonitoringIsUp()throws Exception {
        mockMvc.perform(get("/monitoring"))
                .andExpect(status().isOk());
    }
Run Code Online (Sandbox Code Playgroud)

这里开始问题,我得到错误 引起:org.springframework.beans.factory.UnsatisfiedDependencyException:创建名为'monitoringController'的bean时出错:通过字段'em'表达的不满意的依赖;嵌套异常是 org.springframework.beans.factory.NoSuchBeanDefinitionException:没有可用的“javax.persistence.EntityManager”类型的合格 bean:预计至少有 1 个 bean 有资格作为自动装配候选。依赖注解:{@org.springframework.beans.factory.annotation.Autowired(required=true)}

我想我错过了一些非常简单的东西。任何帮助表示赞赏。

Dja*_*las 6

检查您使用的 spring 版本。在 spring boot 1.4.x 及以上版本中,您只需要:

 @RunWith(SpringRunner.class)
 @SpringBootTest
 public class MonitoringControllerTest {
    // autowire beans and perform tests with @Test  
 }
Run Code Online (Sandbox Code Playgroud)

阅读此Spring Boot 测试改进