Reputation: 12149
I have a simple table called PriceWatch which exists on the database and it has some dummy records in it already setup. I want to create a unit test that will generate an array list of pricewatch items and pass the test if it is not an empty array.
Quite simple on the face of it.. Just read from the database. (im a novice to Spring and Hibernate).. I have tried to cut down the code as much as possible for purpose of the question.
I am getting the following error in my unit test code and im not sure how to get around it.
findAll() can not be referenced from a static context
Here are my code snippets..
PriceWatchTest [src/test/java]
public class PriceWatchTest {
@Test
public static void hasPriceWatchItems() {
List<PriceWatch> priceWatchList = PriceWatchService.findAll();
}
}
PriceWatchService [src/main/java/service]
public interface PriceWatchService {
List<PriceWatch> findAll();
}
PriceWatchServiceImpl [src/main/service/impl]
@Component
public class PriceWatchServiceImpl implements PriceWatchService {
@Autowired
private PriceWatchJpaRepository priceWatchJpaRepository;
@Override
public List<PriceWatch> findAll() {
// Now we can use the dependency
return priceWatchJpaRepository.findAll();
}
}
Upvotes: 0
Views: 544
Reputation: 9586
When the Spring container starts up, it creates a singleton instance of each component. In our case that means that there will be an instance of the concrete version of PriceWatchService that Spring's component scanning finds (in this case PriceWatchServiceImpl), in Springs instantiated beans.
The unit test example provided doesn't start the Spring container. You'll need to annotate the class with:
@RunWith(SpringJUnit4ClassRunner.class)
Now that the Spring container is started, you'll need to inject the service interface and call it from a non static context. Something like this:
@RunWith(SpringJUnit4ClassRunner.class)
public class PriceWatchTest {
@Autowired
private PriceWatchService priceWatchService:
@Test
public static void hasPriceWatchItems() {
List<PriceWatch> priceWatchList = priceWatchService.findAll();
}
}
Upvotes: 1