Spring Boot 2.1测试由于空属性而失败

时间:2018-11-16 07:51:35

标签: java spring unit-testing spring-boot

我不是Spring Boot的专家。我必须为自己的@RestController方法编写测试,但是有一个问题,就是当测试类执行{{1}时,@AutoWired ConfigurationProperties类就是null }。我在这里找到了很多有关类似问题的帖子,但实际上并不能解决这个问题。奇怪的是,在main controller的@PostConstruct方法中,属性类不为null,仅在我尝试测试的@RestController方法中为null。

这是我的@RequestMapping班:

@SpringBootApplication

这是@RestController:

@SpringBootApplication
@ComponentScan
@EnableConfigurationProperties({MysqlProperties.class, CassandraProperties.class, GenericsProperties.class})
@EnableAutoConfiguration
public class REST {
    public static void main(String[] args) {
        SpringApplication.run(REST.class, args);
    }
}

这是@ConfigurationProperties类:

@RestController
public class MainController {

    @Autowired
    private MysqlProperties mysqlProperties;

    @PostConstruct
    public void init() throws Exception {
       //Here mysqlProperties is not null and I can get elements from it
    }

    @RequestMapping(value = "/online", method = RequestMethod.GET)
    public @ResponseBody
    String online(@RequestHeader(value = "email", required = true) String email, @RequestHeader(value = "password", required = true) String password) {
    Utils.logInfo(logger, "/online endpoint");

    //Here mysqlProperties is null
    String sql = "SELECT * FROM " + mysqlProperties.getAddress() + " WHERE email= ?";

    return new Return(Return.ERROR_MESSAGE, "Access denied, not superuser").toString();
}

这是测试:

@Configuration
@PropertySource("classpath:application.properties")
@ConfigurationProperties(prefix = "mysql")
public class MysqlProperties {

    String address;
    String database;
    ...

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public String getDatabase() {
        return database;
    }

    public void setDatabase(String database) {
        this.database = database;
    }
}

这是包的结构:

@RunWith(SpringRunner.class)
@SpringBootTest(classes = {REST.class})
@EnableConfigurationProperties({CassandraProperties.class, GenericsProperties.class, MysqlProperties.class})
@AutoConfigureMockMvc
public class MainControllerTest {

    @Autowired
    private MockMvc mvc;

    @Autowired
    private GenericsProperties genericsProperties;

    @Before
    public void init() {
        try {
            //mc.init();
            mvc = MockMvcBuilders.standaloneSetup(new MainController()).build();
        } catch (Exception ex) {
            ex.printStackTrace();
            Logger.getLogger(MainControllerTest.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    @Test
    public void testOnline() throws Exception {
        //Return returnObject = new Return(Return.DONE_MESSAGE, "System online");
        Return returnObject = new Return(Return.ERROR_MESSAGE, "Access denied, not superuser");

        this.mvc.perform(get("/online")
                .header("email", genericsProperties.getSuperuser_email())
                .header("password", genericsProperties.getSuperuser_password()))
                //.contentType(APPLICATION_JSON))
                .andExpect(status().isOk())
                .andExpect(content().json(returnObject.toString()));
    }
}

NullPointerException发生在MainController类中,位于:

main
--java
----configurations
------MysqlProperties.java
----main
------MainController.java
----...
--resources
----application.properties
test
--java
----main
------MainControllerTest.java

任何线索为什么不起作用?谢谢。

1 个答案:

答案 0 :(得分:0)

@Autowired MysqlProperties mysqlProperties为空,因为您在此处创建了MainController的新实例:
mvc = MockMvcBuilders.standaloneSetup(new MainController()).build();
该实例将不会在Spring上下文中注册,因此将无法用于依赖项注入。
您可以阅读有关此问题的更多信息here

您应该在MainController类中使用自动连接的MainControllerTest

@Autowired
private MainController mainController;