【问题标题】:Spring Junit and annotation based autowiring基于 Spring Junit 和注解的自动装配
【发布时间】:2017-09-29 08:12:47
【问题描述】:

我在一个简单的 spring 示例中添加了一个 junit 测试,但它无法自动装配我编写的 json 服务。

要在春季 JUnit 测试中进行自动装配需要什么?

要尝试失败的项目...

git clone https://bitbucket.org/oakstair/spring-boot-cucumber-example
cd spring-boot-cucumber-example
./gradlew test

提前致谢!

应用

@SpringBootApplication
@ComponentScan("demo")
public class DemoApplication extends SpringBootServletInitializer {

服务接口

@Service
public interface JsonUtils {

    <T> T fromJson(String json, Class<T> clazz);

    String toJson(Object object);

}

服务实现

@Component
public class JsonUtilsJacksonImpl implements JsonUtils {

测试

    @ContextConfiguration()
    @RunWith(SpringJUnit4ClassRunner.class)
    @ComponentScan("demo")
    public class JsonUtilsTest {

       @Autowired
        private JsonUtils jsn;

【问题讨论】:

  • 请将有问题的代码添加到此问题中
  • 您可以通过克隆在 10 秒内获得!在这里粘贴的不是很多,而是很多...
  • @GunnarEketrapp 没有人有时间克隆你的项目......

标签: spring junit autowired


【解决方案1】:

在您的 JsonUtilsTest 中,您不能在此处将 @ComponentScan 放在类级别,因为它不是 @Configuration 类。使用像您在这里使用的 @ContextConfiguration 注释,它首先寻找一个静态内部 @Configuration 类,因此添加一个带有 @ComponentScan 的类,它应该可以工作:

@ContextConfiguration()
@RunWith(SpringJUnit4ClassRunner.class)
public class JsonUtilsTest {

    @Autowired
    private JsonUtils jsn;


    @Test
    // Note: This test is not tested since I haven't got autowiring to work.
    public void fromJson() throws Exception {
        Integer i = jsn.fromJson("12", Integer.class);
        assertEquals(12, (int) i);
    }

    @Test
    // Note: This test is not tested since I haven't got autowiring to work.
    public void toJson() throws Exception {
        assertEquals("12", jsn.toJson(new Integer(12)));
    }

    @Configuration
    @ComponentScan("demo")
    public static class TestConfiguration {
    }

}

编辑:或者您可以通过使用带有 SpringRunner 的 @SpringBootTest 注释来让 Spring Boot 为您完成工作:

@RunWith(SpringRunner.class)
@SpringBootTest
public class JsonUtilsTest {

【讨论】:

    【解决方案2】:

    将此添加到测试类解决了我的问题!

    @ContextConfiguration(classes = {DemoApplication.class})
    

    【讨论】:

      【解决方案3】:

      添加@SpringBootTest

      在你的测试课上 并将您的 SpringBootApplication 类和 Json utils 类提供给 @SpringBootTest 的 classes 字段

      应该是这样的

      @ContextConfiguration()
      @RunWith(SpringJUnit4ClassRunner.class)
      @SpringBootTest(classes={<package>.DemoApplication.class, <package>.JsonUtil.class } )
      @ComponentScan("demo")
      public class JsonUtilsTest {
      

      【讨论】:

        猜你喜欢
        • 2011-03-13
        • 2012-08-13
        • 2011-04-09
        • 1970-01-01
        • 2017-05-27
        • 1970-01-01
        • 2014-09-02
        • 2011-07-29
        • 2011-06-10
        相关资源
        最近更新 更多