Chciałbym przetestować przykładową metodę myMethod która jest bardzo podobna do takiej którą napisałem w rzeczywistości.
Głównym moim problemem jest to że nie wiem czy uwzględniać w testach obiekty lokalne, tu dwa obiekty Calendar. A jeśli uwzględniać to jak testować.
public class MyClass {
private ArrayList<Something> somethingList;
public MyClass (ArrayList<Something> somethingList) {
this.somethingList = somethingList;
}
public void myMethod() {
for (Something something : somethingList) {
if (something.isVariableSet()) {
Calendar expectedTime = something.getMyCalendar();
Calendar now = Calendar.getInstance();
if (now.after(expectedTime)) {
File mf = something.getMyFile();
if (something.isReady()) {
MySpecialThread mst = new MySpecialThread(mf);
Thread th = new Thread(mst);
th.start();
}
}
}
}
}
}
Oto "zebrane" moje próby testowania tej metody.
public class MyClassTest {
ArrayList<Something> somethingList = new ArrayList<Something>();
Something np1;
Something np2;
@Before
public void setUp(){
np1 = createMock(Something.class);
np2 = createMock(Something.class);
somethingList.add(np1);
somethingList.add(np2);
}
@Test
public void testMyMethod() {
MyClass ctt = new MyClass(somethingList);
expect(np1.isVariableSet()).andReturn(true);
Calendar expectedTime = createMock(Calendar.class);
Calendar now = createMock(Calendar.class);
//czy powinienem ustawić
// expectedTime.set(2011, 12, 12);
// now.set(2010, 12, 17);
expect(np1.getMyCalendar()).andReturn(expectedTime);
expect(Calendar.getInstance()).andReturn(now);
expect(now.after(expectedTime)).andReturn(true);
File mf = createMock(File.class);
expect(np1.getMyFile()).andReturn(mf);
expect(np1.isReady()).andReturn(true);
MySpecialThread mst = createMock(MySpecialThread.class);
Thread th = createMock(Thread.class);
expect(th.start());
EasyMock.replay(np1);
EasyMock.replay(expectedTime);
EasyMock.replay(now);
EasyMock.replay(mf);
EasyMock.replay(mst);
EasyMock.replay(th);
ctt.myMethod();
EasyMock.verify(np1);
EasyMock.verify(expectedTime);
EasyMock.verify(now);
EasyMock.verify(mf);
EasyMock.verify(mst);
EasyMock.verify(th);
}
}
Przy ctt.myMethod(); leci Unexpected method clone().
Czy typy jak Calendar czy File też powinny być mockami?
Co robić z takimi lokalnymi obiektami, brać pod uwagę przy testowaniu czy nie?
Nie wiem w ogóle czy mój tok myślenia jest prawidłowy, dlatego jeśli ktoś miałby chęć i czas, prosiłbym o sprawdzenie tego mojego testu, czy ja w ogóle się do tego prawidłowo zabieram.