I have a class A
that needs to the tested. The following is the definition of A
:
public class A {
public void methodOne(int arg
The best way to deal with such a problem is to use an injected Clock
service, used to get new instances of DateTime. That way, your test can inject a mock Clock, which returns a specific DateTime instead of the current time.
Note that the new Java 8 time API defines such a Clock class, specifically for that purpose.
You cannot mock a local variable. What you could do, however, is extract its creation to a protected
method and spy
it:
public class A {
public void methodOne(int argument) {
//some operations
methodTwo(int argument);
//some operations
}
private void methodTwo(int argument) {
DateTime dateTime = createDateTime();
//use dateTime to perform some operations
}
protected DateTime createDateTime() {
return new DateTime();
}
}
public class ATest {
@Test
public void testMethodOne() {
DateTime dt = new DateTime (/* some known parameters... */);
A a = Mockito.spy(new A());
doReturn(dt).when(a).createDateTime();
int arg = 0; // Or some meaningful value...
a.methodOne(arg);
// assert the result
}
Sorry for the late reply.
This might be too much of a hassle, but if you mock the object that can give you the local variable, you can return a mock of it. I'd rather not restructure the code to make testing easier, but its something to consider.
public class A {
DateTimeFactory factory;
private void method() {
DateTime dateTime = factory.getDateTime();
//use dateTime to perform some operations
}
}
In your test you can do something like: when(factoryMock.getDateTime()).doReturn(dateTimeMock)
The factory mock would need to be injected into the class somehow.