Basically I want to run the test on a clean slate, so I don't want @PostConstruct populating the data field.
I have a private static variable in service class that gets data loaded from the repository upon build success. Is there a way to run unit tests without this data? (with fresh classes)
In the test I'm mocking a repository's getData
function but there is an if empty
statement in there. Since on build, the static variable is populated the tests won't use the mocked function, so the test fails.
What I found works is to call an empty variable
function of the service within a @Before
annotation. But this is not a stable solution.
sample of code:
private static List<Data> data = Collections.synchronizedList(new ArrayList<Data>());
@PostConstruct
private List<Data> populateData() {
data = repo.findData();
return data;
}
public List<Data> getData() {
if (data.size() == 0) {
populateData();
}
return data;
}
test:
@Mock
private Repository repo;
@Mock
private static Data data;
@InjectMocks
private Service service;
private List<Data> rows = new ArrayList<Data>();
@Before
public void mockMethodSetup() {
//service.evictData();
data.setValue(1);
when(repo.findData()).thenReturn(data);
}
@Test
public void shouldReturnDataResponse() {
List<Data> dataReturned= service.getData();
assertEquals("Response was not equal to the mock.", dataReturned, data);
}