I am new, working with Spring Boot. I am writing a unit test and I always got the following exception:
java.lang.NullPointerException: Cannot invoke "com.trivadis.stocks.service.InitializeService.createInitialStocks()" because "this.initializeService" is null
I have no idea what I can do. I think that the @AutoWired doesn't work.
The source code of my test:
import com.trivadis.stocks.entity.Stock;
import com.trivadis.stocks.repository.StockRepository;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.RepeatedTest;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import static org.junit.jupiter.api.Assertions.*;
class StockServiceTest {
private Stock stock1;
private Stock stock2;
@Autowired
StockService stockService;
@Autowired
InitializeService initializeService;
@Autowired
StockRepository stockRepository;
/**
* initializes the needed stock objects and the stockService before any test will be run
*/
@BeforeEach()
public void init() {
initializeService.createInitialStocks();
stock1 = stockService.getById(1L);
//stock2 = new Stock("stock1", 2999.98);
}
/**
* Is a test, which will be executed 500 times
* it tests if the interval of the created random number is correct.
*/
@RepeatedTest(1)
void changePrice() {
stockService.changePrice(stock1.getId(), 1, true);
System.out.println(stock1.getPrice());
// assertTrue(stock1.getPrice() >= 1.025);
//System.out.println(stock1.getPrice());
//assertTrue(stock1.getPrice() <= 1.15);
}}