jdbcTemplate.getDataSource()在我的单元测试中始终为null

时间:2018-08-02 15:37:01

标签: java spring-boot junit

我是为Spring Boot应用编写junit测试的新手。有人可以帮助我了解情况吗?

我有一项要测试的服务:

@Service
public class MyService {
    private final JdbcTemplate jdbcTemplate;
    …    
    @Autowired
    public MyService(JdbcTemplate jdbcTemplate){
        this.jdbcTemplate = jdbcTemplate;
        …
    }
    @Async
    public SomeType myMethod(SomeDTO request) {
        DataSource dataSource = this.jdbcTemplate.getDataSource();
        …
    }
    …
}

当我启动我的应用程序并通过REST API调用服务时,我的数据源是正确的,并且基于application.yml中的参数。

但是,当我从单元测试中调用它时,this.jdbcTemplate.getDataSource()始终为空。

这是我的考试班:

SpringBootTestApplication:

@RunWith(SpringRunner.class)
@SpringBootTest(
        classes = TestConfigurator.class
)
public abstract class SpringBootTestApplication {
}

MyServiceTest:

    public class MyServiceTest  extends SpringBootTestApplication {

        @MockBean
        private JdbcTemplate jdbcTemplate;


        @Autowired
        @InjectMocks
        private MyService myService;

        @Test
        public void Test_1(){
            DataSource dataSource = this.jdbcTemplate.getDataSource();
myService.getSomething(dataSource, ...)
             …
        }


    }

我应该在我的TestConfigurator.class中添加一些特殊的东西吗?

1 个答案:

答案 0 :(得分:0)

    public class MyServiceTest  extends 
    SpringBootTestApplication {

    @MockBean
    private JdbcTemplate jdbcTemplate;

   private MyService myService;  

    @Before
     public void init(){
        myService = new MyService(this.jdbcTemplate);
   }

    @Test
    public void Test_1(){
       DataSource datasource = new DataSource());  
       when.jdbcTemplate.getDatasource()).thenReturn(datasource);
       myService.getSomething(dataSource, ...)
         …
    }


}