【问题标题】:Autowire not working in Spring testAutowire 在 Spring 测试中不起作用
【发布时间】:2017-03-03 07:57:56
【问题描述】:

我创建了一个简单的 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());
    }

问题从这里开始,我遇到了错误 原因: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)}

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

【问题讨论】:

    标签: spring testing autowired


    【解决方案1】:

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

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

    阅读此spring boot tests improvments

    【讨论】:

      【解决方案2】:

      找到了解决方案。添加了 @EnableAutoConfiguration 来解决 EntityManager 问题。

      【讨论】:

      • 你在哪里添加的?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-08-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多