简体   繁体   中英

[Play framework ]DataBase connection in tests returns null

I have a model that looks like this

public class Student extends User {
    public void someFunction(){
          Connection conn=DB.getConnection();
              .......
      }
  }

This works just fine when I run it within the application

However it throws A null exception when it get invoked by a unit test

here is the stack trace :

java.lang.NullPointerException
at play.api.Application$$anonfun$instanceCache$1.apply(Application.scala:215)
at play.api.Application$$anonfun$instanceCache$1.apply(Application.scala:215)
at play.utils.InlineCache.fresh(InlineCache.scala:69)
at play.utils.InlineCache.apply(InlineCache.scala:55)
at play.api.db.DB$.db(DB.scala:24)
at play.api.db.DB$.getConnection(DB.scala:35)
at play.api.db.DB.getConnection(DB.scala)
at play.db.DB.getConnection(DB.java:79)
at play.db.DB.getConnection(DB.java:67)
at play.db.DB.getConnection(DB.java:46)

I guess you inject DB object to Student. If so, within application it works fine because Play init a DB object then inject it into Student. So you can use DB object.

In unit test, you call someFunction() function directly so DB object is null (which cause NullPointException).

I think in unit test, you should init DB before call someFunction() function.

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