2015-10-28 128 views
1

我有點新Scala和標題中所說,我試圖嘲笑一個類。Mockito類被嘲笑,但沒有返回任何東西

DateServiceTest.scala

@RunWith(classOf[JUnitRunner]) 
class DateServiceTest extends FunSuite with MockitoSugar { 
    val conf = new SparkConf().setAppName("Simple Application").setMaster("local") 
    val sc = new SparkContext(conf) 
    implicit val sqlc = new SQLContext(sc) 

    val m = mock[ConfigManager] 
    when(m.getParameter("dates.traitement")).thenReturn("10") 

    test("mocking test") { 

    val instance = new DateService 
    val date = instance.loadDates 
    assert(date === new DateTime()) 
    } 
}  

DateService.scala

class DateService extends Serializable with Logging { 

    private val configManager = new ConfigManager 
    private lazy val datesTraitement = configManager.getParameter("dates.traitement").toInt 

    def loadDates() { 
    val date = selectFromDatabase(datesTraitement) 
    } 
} 

不幸的是,當我運行測試,datesTraitement返回null,而不是10,而是m.getparameter(」 dates.traitement「)確實返回10.

也許我在某處做某種反模式,但我不知道在哪裏,請記住,我是新的所有這一切,我沒有找到任何具體的例子特定於我的情況在互聯網上。

感謝您的任何幫助。

回答

3

我覺得問題是你的模擬沒有注入,因爲你在DateService類中創建了ConfigManager內聯。取而代之的

class DateService extends Serializable with Logging { 
    private val configManager = new ConfigManager 
} 

嘗試

class DateService(private val configManager: ConfigManager) extends Serializable with Logging 

並在測試情況下注入嘲笑CONFIGMANAGER當你構建DateService

class DateServiceTest extends FunSuite with MockitoSugar { 
    val m = mock[ConfigManager] 
    val instance = new DateService(m) 
}