Spring Junit和基于注释的自动装配

时间:2017-09-29 08:12:48

标签: spring junit autowired

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

在Spring 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;

3 个答案:

答案 0 :(得分: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启动为你工作:

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

答案 1 :(得分:0)

将此添加到测试类修复了我的问题!

@ContextConfiguration(classes = {DemoApplication.class})

答案 2 :(得分:0)

添加@SpringBootTest

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

看起来应该是这样的

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