Home > Enterprise >  Testing service that has attribut Repository that implements CrudRepository<> in
Testing service that has attribut Repository that implements CrudRepository<> in

Time:01-09

I want to test this service that uses 3 repositorie implementing CrudRepository of JPA

@Service
public class ExpeditionService {
    ArticleRepository articleRepository;
    CustomerRepository customerRepository;
    AdressRepository adressRepository;

    public ExpeditionService(ArticleRepository articleRepository, CustomerRepository customerRepository, AdressRepository adressRepository) {
        this.articleRepository = articleRepository;
        this.customerRepository = customerRepository;
        this.adressRepository = adressRepository;
    }

    public Set<Article> findArticleByOrderId(Long orderId) {
        return articleRepository.findArticleByOrdersId(orderId);
    }

    public Optional<Customer> findCustomerById(Long customerId) {
        return customerRepository.findById(customerId);
    }

    public Set<Adress> findAdressesByOrderId(Long orderId) {
        return adressRepository.findAdressesByOrOrderAdressesId(orderId);
    }
}

In my test I set up ExpeditionService and repositories

@ExtendWith(SpringExtension.class)
@DataJpaTest
public class ExpeditionServiceTest {
    @Autowired
    private ArticleRepository articleRepository;
    @Autowired
    private TypeAdresseRespository typeAdresseRespository;
    @Autowired
    private AdressRepository adressRepository;
    @Autowired
    OrderRepository orderRepository;
    @Autowired
    CustomerRepository customerRepository;
    @Autowired
    CountryRepository countryRepository;
    ExpeditionService expeditionService = new ExpeditionService(articleRepository , customerRepository , adressRepository);
}

But when I launch test on no matter what kind of method I'm getting error that this repository is null What should I do please?

CodePudding user response:

Please rewrite your unit test case like this and try again.

@ExtendWith(MockitoExtension.class)
public class ExpeditionServiceTest {
    
    @Mock
    private ArticleRepository articleRepository;
    
    @Mock
    private AdressRepository adressRepository;
    
    @Mock
    CustomerRepository customerRepository;
    
    ExpeditionService expeditionService;

    @BeforeEach
    void setUp(){
    expeditionService = new ExpeditionService(articleRepository , customerRepository , adressRepository);
    }

    @Test
    void test1() {
       //test code
    }
}
  • Related