2

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);
    }}
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197

1 Answers1

2

Great, you are writing tests!

Unfortunately, Autowired does not work like that, you will need the spring-context which you don't really need if you writing simple unit-tests.

Regarding your unit-test, you are testing StockServiceTest so you should focus only on that class StockService and mock the behaviour of InitializeService and StockRepository. I would recommend a quick read of this tutorial.

For mocking, you can use Mockito

If you want to test both classes, you can initialize them inside the init() method but you will have to handle the dependencies they might have.

Andre
  • 70
  • 5