简体   繁体   中英

Spring JUnit tests .. autowire not working

Hoping for some help discovering why these tests throw errors..

I've written a Spring Boot RESTful app. I have integration tests written in JUnit which work (reading the configuration from application.properties)

The Controller calls a class which contains the database access

Testing the controller works fine.. when I try to test the database access class directly.. I get a BindException Failed to bind properties under 'spring.datasource'

 @RequestMapping("/{source}/product")
Result prodBySource(@PathVariable String source, @RequestParam String prodId) throws Exception {
    logger.debug(String.format("GET Product %s from %s. ", source, prodId)) ;

    return productDb.getProd(prodId);

}

The productDb has

protected String getJson(String prodId) {
    MapSqlParameterSource params = new MapSqlParameterSource()
            .addValue("product_id", prodId);
    String jsonString = "{}" ; 

    String jsonString = jdbcTemplate.queryForObject(query, params, 
            (rs, rowNum) -> {
                return rs.getString("json_data") ; 

            });

    return jsonString;
}

public Result getProd(String prodId) {
    String jsonString = getJson(prodId);
    Object jsonNode = JsonPath.parse(jsonString).json();
    Result res = new Result(prodId, jsonNode) ; 
    return res;
}

The JUnit test has

@RunWith(SpringRunner.class)
@SpringBootTest(classes= {ProductDb.class, AppConfig.class}) 
@TestPropertySource(locations = 
"classpath:/com/broadridge/adc/fasttests/product/application- 
fasttests.properties")
@ConfigurationProperties(prefix="spring.datasource")
@Category(com.broadridge.adc.product.FastTests.class)
public class ProductDbTest implements FastTests {

@Autowired
ProductDb lipperProductDb ; 

@Test
public void getJson() throws Exception {


    Result json = 
     lipperProductDb.getProd("30027978") ; 
    Supplier<String> messageSupplier = () -> {
        return "Json can't be null";
    };
    Assert.notNull(json, messageSupplier);
}

May be you are autowiring interface rather than a implementation class. If you test DAO Layer should mock repository/dao object. No actual database call should be made during testing that layer rather autowiring the actual dao object you should mock the ProductDb and use Mockito when(), thenReturn().

 @RunWith(SpringRunner.class)
    @SpringBootTest(classes= {ProductDb.class, AppConfig.class}) 
    @TestPropertySource(locations = 
    "classpath:/com/broadridge/adc/fasttests/product/application- 
    fasttests.properties")
    @ConfigurationProperties(prefix="spring.datasource")
    @Category(com.broadridge.adc.product.FastTests.class)
    public class ProductDbTest implements FastTests {

    @Mock
    ProductDb lipperProductDb ; 

    @Test
    public void getJson() throws Exception {
      Result resultJson = new Result()//some result object
      when(lipperProductDb.getProd("30027978")).thenReturn(resultJson);

        Result json = 
         lipperProductDb.getProd("30027978") ; 
        Supplier<String> messageSupplier = () -> {
            return "Json can't be null";
        };

        Assert.notNull(json, messageSupplier);
    } 

我不知道为什么,但是删除@ConfigurationProperties(prefix="spring.datasource")解决此问题。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM