@Inject
private Accessor accessor;
@Dependent
public class DataReader {
String getData(String key) {
String value = accessor.getByDate(key, new Date());
return value;
}
}
public class DataReaderTest {
@Mock
Accessor accessor;
@InjectMocks @Spy
DataReader dataReader;
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
}
@Test
public void test() {
when(accessor.getByDate(key, new Date())).thenReturn(now);
assertThat(dataReader.getData("key0"), is("todayData"));
}
}
when (accessor.getByDate (key, new Date ())). thenReturn (now);
is actually called ʻaccessor.getByDate (key, getNow ())`, the value of the Date type argument changes. I failed because I ended up@Inject
private Accessor accessor;
@Dependent
public class DataReader {
String getData(String key) {
String value = accessor.getByDate(key, getNow());
return value;
}
Date getNow() {
return new Date();
}
}
public class DataReaderReaderTest {
@Mock
Accessor accessor;
@InjectMocks @Spy
DataReader dataReader;
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
}
@Test
public void test() {
Date now = new Date();
//This is also good
//when(deviceOptionReader.getNow()).thenReturn(now);
doReturn(now).when(deviceOptionReader).getNow();
when(accessor.getByDate(key, now)).thenReturn(now);
assertThat(dataReader.getData("key0"), is("todayData"));
}
}
Do not write code that creates a new Date type directly in the method argument
Recommended Posts