In my code I have something like this:
private void doSomething() {
Calendar today = Calendar.getInstance();
....
}
How can I “mock” it in my junit test to return a specific date?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
As far as I see it you have three sensible options:
Inject the
Calendarinstance in whatever method/class you set that day in.private void method(final Calendar cal){
Date today = cal.getTime();
}
Use JodaTime instead of
Calendar. This is less an option and more a case of a suggestion as JodaTime will make your life a lot easier. You will still need to inject this time in to the method.DateTime dt = new DateTime();Date jdkDate = dt.toDate();Wrap
Calendarinside some interface that allows you to fetch the time. You then just mock that interface and get it to return a constantDate.Date today = calendarInterfaceInstance.getCurrentDate()