Clarification in Java Code Testing
java, spring
Solution
My initial thought is that it is difficult to test because the "RescureDamselQuest" object is initialized in the constructor. This makes it difficult to for example insert a mock object. A mock object would help you test that the embark() method is called on the "RescueDamselQuest" object.
A better way to solve this can be to either include a parameter in the constructor (usually I prefer this method):
public DamselRescuingKnight(RescueDamselQuest quest){
this.quest = quest;
}
Or add a setter:
public void setDamselRescuingKnight(RescueDamselQuest quest){
this.quest = quest;
}
Problem
I have started reading the Spring in Action book. I have no knowledge of JUnit which I think my doubt is about. There is a code fragment where the author refers to and says that it is difficult to test: ``` package com.springinaction.knights; public classDamselRescuingKnight implements Knight { private RescueDamselQuest quest; public DamselRescuingKnight() { quest = new RescueDamselQuest(); } public voidembarkOnQuest() throwsQuestException { quest.embark(); } } ``` The author says that: It’d be terribly difficult to write a unit test for DamselRescuingKnight. In such a test, you’d like to be able to assert that the quest’s embark() method is called when the knight’s embarkOnQuest() is called. But there’s no clear way to accomplish that here. Unfortunately, DamselRescuingKnight will remain untested. What does the author mean by this? Why is the code difficult to test here?