Adding unit test example

This commit is contained in:
alex 2024-05-22 22:53:33 -04:00
parent 383e4d6fe4
commit 3634da20f6
6 changed files with 86 additions and 61 deletions

View File

@ -230,6 +230,12 @@
<version>5.12.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-junit-jupiter</artifactId>
<version>5.12.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-checkstyle-plugin</artifactId>

View File

@ -7,8 +7,7 @@ import jakarta.transaction.Transactional;
import lombok.Data;
import lombok.extern.log4j.Log4j2;
import org.hibernate.search.mapper.orm.Search;
import org.hibernate.search.mapper.orm.massindexing.MassIndexer;
import org.hibernate.search.mapper.orm.session.SearchSession;
import org.jetbrains.annotations.NotNull;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;
@ -23,11 +22,11 @@ public class ApplicationReadyListener implements ApplicationListener<Application
@Override
@Transactional
public void onApplicationEvent(final ApplicationReadyEvent event) {
public void onApplicationEvent(final @NotNull ApplicationReadyEvent event) {
var indexed = new Class[]{Client.class, Product.class};
log.info("Indexing tables {}", Arrays.stream(indexed).toList());
SearchSession searchSession = Search.session(entityManager);
MassIndexer indexer = searchSession.massIndexer(indexed)
var searchSession = Search.session(entityManager);
var indexer = searchSession.massIndexer(indexed)
.threadsToLoadObjects(4);
try {

View File

@ -3,14 +3,10 @@ package com.primefactorsolutions.invoices.services;
import com.primefactorsolutions.invoices.data.ClientRepository;
import com.primefactorsolutions.invoices.model.Client;
import com.primefactorsolutions.invoices.model.Status;
import jakarta.persistence.EntityManager;
import jakarta.transaction.Transactional;
import lombok.Data;
import lombok.extern.log4j.Log4j2;
import org.apache.logging.log4j.util.Strings;
import org.hibernate.search.engine.search.query.SearchResult;
import org.hibernate.search.mapper.orm.Search;
import org.hibernate.search.mapper.orm.session.SearchSession;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
@ -22,7 +18,7 @@ import java.util.UUID;
@Log4j2
public class ClientService {
private final ClientRepository clientRepository;
private final EntityManager entityManager;
private final SearchService searchService;
private final CompanyService companyService;
@Transactional
@ -36,15 +32,8 @@ public class ClientService {
return clientRepository.findAll();
}
SearchSession searchSession = Search.session(entityManager);
SearchResult<Client> result = searchSession.search(Client.class)
.where(f -> f.match()
.fields("nombreRazonSocial", "correoElectronico")
.matching(code))
.fetch(20);
var result = searchService.search(Client.class, List.of("nombreRazonSocial", "correoElectronico"), code);
long totalHitCount = result.total().hitCount();
log.info("Found {} results", totalHitCount);
return result.hits();

View File

@ -1,6 +1,5 @@
package com.primefactorsolutions.invoices.services;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.openhtmltopdf.pdfboxout.PdfBoxRenderer;
import com.openhtmltopdf.pdfboxout.PdfRendererBuilder;
@ -18,6 +17,7 @@ import freemarker.template.TemplateExceptionHandler;
import jakarta.transaction.Transactional;
import lombok.Data;
import lombok.Getter;
import lombok.SneakyThrows;
import lombok.extern.log4j.Log4j2;
import org.apache.pdfbox.io.MemoryUsageSetting;
import org.apache.pdfbox.pdmodel.PDDocument;
@ -48,8 +48,8 @@ public class InvoiceService {
}
@Transactional
@SneakyThrows
public void sendInvoice(final FacturaComputarizadaComercialExportacionServicio factura) {
try (var os = new ByteArrayOutputStream()) {
writeAsPdf(factura, os);
var media = new Media();
@ -57,8 +57,6 @@ public class InvoiceService {
media.setContent(os.toByteArray());
mediaRepository.save(media);
} catch (IOException e) {
// no-op
}
var invoice = new Invoice();
@ -66,17 +64,11 @@ public class InvoiceService {
invoice.setFechaEmision(LocalDateTime.ofInstant(Instant.now(), ZoneId.of("UTC")));
invoice.setCompany(companyService.getCompany());
invoice.setNombreRazonSocial(factura.getCabecera().getNombreRazonSocial());
try {
invoice.setPayload(objectMapper.writeValueAsString(factura));
} catch (JsonProcessingException e) {
log.info("Error writing invoice JSON");
}
invoice.setPayload(objectMapper.writeValueAsString(factura));
invoiceRepository.save(invoice);
}
protected static InputStream getTemplate() {
return getDefaultTemplate();
}
@ -85,39 +77,34 @@ public class InvoiceService {
return Invoice.class.getResourceAsStream("/pfs-invoice.html");
}
@SneakyThrows
public void writeAsPdf(final FacturaComputarizadaComercialExportacionServicio factura, final OutputStream out) {
try {
var in = getTemplate();
Configuration cfg = getConfiguration();
var in = getTemplate();
Configuration cfg = getConfiguration();
Reader reader = new InputStreamReader(in);
Template temp = new Template("pfs-invoice", reader, cfg);
Reader reader = new InputStreamReader(in);
Template temp = new Template("pfs-invoice", reader, cfg);
DefaultObjectWrapper wrapper = new DefaultObjectWrapper();
ByteArrayOutputStream oo = new ByteArrayOutputStream();
Writer outTemplate = new OutputStreamWriter(oo);
var wrapper = new DefaultObjectWrapper(Configuration.VERSION_2_3_32);
ByteArrayOutputStream oo = new ByteArrayOutputStream();
Writer outTemplate = new OutputStreamWriter(oo);
temp.process(wrapper.wrap(factura), outTemplate);
temp.process(wrapper.wrap(factura), outTemplate);
PdfRendererBuilder builder = new PdfRendererBuilder();
builder.usePDDocument(new PDDocument(MemoryUsageSetting.setupMixed(1000000)));
builder.withHtmlContent(oo.toString(StandardCharsets.UTF_8), "/test");
builder.toStream(out);
var builder = new PdfRendererBuilder();
builder.usePDDocument(new PDDocument(MemoryUsageSetting.setupMixed(1000000)));
builder.withHtmlContent(oo.toString(StandardCharsets.UTF_8), "/test");
builder.toStream(out);
try (PdfBoxRenderer pdfBoxRenderer = builder.buildPdfRenderer()) {
pdfBoxRenderer.layout();
pdfBoxRenderer.createPDF();
}
} catch (Exception ex) {
throw new RuntimeException(ex);
try (PdfBoxRenderer pdfBoxRenderer = builder.buildPdfRenderer()) {
pdfBoxRenderer.layout();
pdfBoxRenderer.createPDF();
}
}
@NotNull
private static Configuration getConfiguration() {
Configuration cfg = new Configuration(Configuration.VERSION_2_3_32);
// cfg.setDirectoryForTemplateLoading(new File("/where/you/store/templates"));
// Recommended settings for new projects:
var cfg = new Configuration(Configuration.VERSION_2_3_32);
cfg.setDefaultEncoding("UTF-8");
cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
cfg.setLogTemplateExceptions(false);

View File

@ -0,0 +1,25 @@
package com.primefactorsolutions.invoices.services;
import jakarta.persistence.EntityManager;
import lombok.Data;
import org.hibernate.search.engine.search.query.SearchResult;
import org.hibernate.search.mapper.orm.Search;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
@Data
public class SearchService {
private final EntityManager entityManager;
public <T> SearchResult<T> search(final Class<T> clazz, final List<String> fields, final String query) {
var searchSession = Search.session(entityManager);
return searchSession.search(clazz)
.where(f -> f.match()
.fields(fields.toArray(new String[0]))
.matching(query))
.fetch(20);
}
}

View File

@ -1,22 +1,41 @@
package com.primefactorsolutions.invoices.services;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import com.primefactorsolutions.invoices.data.ClientRepository;
import com.primefactorsolutions.invoices.model.Client;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import java.util.Optional;
import java.util.UUID;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.when;
@ExtendWith(MockitoExtension.class)
class ClientServiceTest {
@BeforeEach
void setUp() {
}
@AfterEach
void tearDown() {
}
@InjectMocks
ClientService clientService;
@Mock
ClientRepository clientRepository;
@Mock
SearchService searchService;
@Mock
CompanyService companyService;
@Test
void getClient() {
var id = UUID.randomUUID();
var client = new Client();
client.setId(id);
when(clientRepository.findById(eq(id))).thenReturn(Optional.of(client));
var found = clientService.getClient(id);
assertEquals(client.getId(), found.getId());
}
}