Stworzyłem taki kod:
package service;
import entity.Product;
import org.junit.Before;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import static org.junit.Assert.*;
public class ProductServiceTest {
List<Product> products;
ProductServiceImpl service;
@Before
public void is(){
products.clear();
products = List.of(
new Product(1l,"a", 20.0f, 30.0f, "red", Integer.valueOf(5)),
new Product(2l,"b", 20.0f, 30.0f, "red", Integer.valueOf(5)));
service = new ProductServiceImpl(products);
}
@Test
public void getCountOfProductsZeroTest() {
ProductServiceImpl emptyService = new ProductServiceImpl(new ArrayList<>());
assertEquals(Integer.valueOf(0), emptyService.getCountOfProducts());
}
@Test
public void getCountOfProductsNormalTest() {
assertEquals(Integer.valueOf(2), service.getCountOfProducts());
}
@Test
public void getByNameIfExistTest() {
assertEquals(products.get(0), service.getByName("a"));
}
@Test
public void getByNameIfNotExistTest() {
assertEquals(null, service.getByName("d"));
}
@Test
public void isProductAvailableIfTrueTest() {
assertTrue(service.isProductAvailable("a"));
}
@Test
public void isProductAvailableIfFalseTest() {
assertFalse(service.isProductAvailable("d"));
}
@Test
public void isProductExistByNameIfTrueTest() {
assertTrue(service.isProductExist("a"));
}
@Test
public void isProductExistByNameIfFalseTes() {
assertFalse(service.isProductExist("d"));
}
@Test
public void IsProductExistByIdIfTrueTest() {
assertTrue(service.isProductExist(1l));
}
@Test
public void IsProductExistByIdIfFalseTes() {
assertFalse(service.isProductExist(4l));
}
}
Jeśli treść z metody is() przekopiuję do każdego z testów, to maven nie rzuca żadnym błędem. Teraz jednak rzuca NullPointerException. Powtarzanie kodu źle wygląda, dlatego chciałbym się dowiedzieć dlaczego to nie działa (najlepiej z wytłumaczenie, a nie po prostu zmień to i to) i jak to ewentualnie naprawić.
Z góry dziękuję za pomoc.
Ps. Używam Intellji Idea 2020.1.2, mavena z compilatorem w wersji 1.9, Javy 9 i JUnit 4