How to write unit test (via Junit) for MongoTemplate updateFirst() method ?
I have this service class:
#Service
public class TemplateServiceImpl implements TemplateService
{
#Resource
private TemplateRepository templateRepository;
#Resource
private MongoTemplate mongoTemplate;
#Override
public TemplateDto create(TemplateDto templateDto)
{
TemplateDto result;
templateDto.setDeleted(false);
result = templateRepository.insert(templateDto);
return result;
}
#Override
public boolean update(ObjectId id, TemplateDto templateDto)
{
if (templateDto != null)
{
Update update = new Update();
if (templateDto.getName() != null)
{
update.set("name", templateDto.getName());
}
if (templateDto.getTemplate() != null)
{
update.set("template", templateDto.getTemplate());
}
if (templateDto.isDeleted())
{
update.set("deleted", Boolean.TRUE);
}
update.set("lastUpdate", new Date());
return mongoTemplate.updateFirst(new Query(Criteria.where("_id").is(id)), update, "template")
.wasAcknowledged();
}
return false;
}
}
I want write unit test for update method . This is my relevant test class:
#ExtendWith(MockitoExtension.class)
class TemplateServiceImplTest
{
#InjectMocks
private static TemplateServiceImpl templateService;
#Mock
private static TemplateRepository templateRepository;
#Mock
private static MongoTemplate mongoTemplate;
private static TemplateDto templateDto;
private static List<TemplateDto> listOfTemplates;
private static String requestBody;
#BeforeAll
private static void setUp(){
templateDto = createTemplateDto();
listOfTemplates = createListOfTemplate();
requestBody = createRequesyBody();
}
#Test
void create()
{
when(templateRepository.insert(templateDto)).thenReturn(templateDto);
TemplateDto actualResult = templateService.create(TemplateServiceImplTest.templateDto);
assertThat(actualResult).isNotNull();
assertThat(actualResult).isInstanceOf(TemplateDto.class);
assertThat(actualResult.getId()).isEqualTo(templateDto.getId());
}
#Test
void update()
{
Update update = new Update();
/*
when(mongoTemplate.updateFirst(new Query(Criteria.where("_id").is(templateDto.getId().toString())) ,update , TemplateDto.class)).thenReturn(
UpdateResult.acknowledged());
*/
/*
given(mongoTemplate.updateFirst(new Query(Criteria.where("_id").is(templateDto.getId().toString())) ,update , TemplateDto.class));
*/
boolean actualResult = templateService.update(templateDto.getId(), templateDto);
assertThat(actualResult).isNotNull();
assertThat(actualResult).isTrue();
}
// other methods...
}
When I run test I get NPE for mongoTemplate at update method , I searched and I saw this 2 approach:
when(mongoTemplate.updateFirst(new Query(Criteria.where("_id").is(templateDto.getId().toString())) ,update , TemplateDto.class)).thenReturn(
UpdateResult.acknowledged());
Or
given(mongoTemplate.updateFirst(new Query(Criteria.where("_id").is(templateDto.getId().toString())) ,update , TemplateDto.class));
But none of them worked .
actually how to test MongoTemplate updateFirst method?
Thanks
Related
I have a spring-boot application.
I have entity:
#Data
#Builder
#NoArgsConstructor
#AllArgsConstructor
#Document(COLLECTION_NAME)
public class PersonEntity {
public static final String COLLECTION_NAME = "person_info";
private static final String PERSON_NAME = "person_name";
#Id
private PersonId id;
#Field(name = PERSON_NAME)
private String personName;
#Indexed(name = "ttl_index", expireAfterSeconds=20)
private LocalDateTime date;
}
I have a repository interface:
public interface PersonRepository {
void saveWithTtl(PersonEntity entity);
}
The repository implementation:
#Slf4j
#Repository
public class PersonRepositoryImpl implements PersonRepository {
private final int expireAfterSeconds;
private final ReactiveMongoTemplate mongoTemplate;
public PersonRepositoryImpl(#Value("${ttl.index}") int expireAfterSeconds,
ReactiveMongoTemplate mongoTemplate) {
this.expireAfterSeconds = expireAfterSeconds;
this.mongoTemplate = mongoTemplate;
}
#Override
public void saveWithTtl(PersonEntity entity) {
mongoTemplate.indexOps(PersonEntity.class)
.ensureIndex(new Index().on(PersonEntity.CREATED_AT, ASC)
.expire(expireAfterSeconds)).subscribe(result -> log.info("Ttl index has been created: {}", result));
mongoTemplate.save(entity).subscribe(result -> log.info("Entity has been saved: {}", result));
}
}
And, finally, I have test that does not work:
#DataMongoTest
#Testcontainers
public class PersonRepositoryIT {
#Autowired
private ReactiveMongoTemplate mongoTemplate;
#Autowired
private PersonRepository repository;
#Container
private static MongoDbContainer mongoDbContainer = new MongoDbContainer();
#AfterEach
void cleanUp() {
repository.deleteAll();
}
#DynamicPropertySource
static void registerMongoProperties(DynamicPropertyRegistry registry) {
registry.add("spring.data.mongodb.uri", mongoDbContainer::getReplicaSetUrl);
}
#Test
public void shouldCreateAndDeleteRecordsAfterDelay_whenSaveWithTtl_givenDefinedTll() {
//given
PersonEntity givenEntity = PersonEntity.builder().createdAt(LocalDateTime.now())
.personName("Joe")
.id(PERSON_ID).build();
//when
repository.saveWithTtl(givenEntity);
//then
StepVerifier.create(mongoTemplate.estimatedCount(PersonEntity.COLLECTION_NAME))
.expectNext(1L)
.verifyComplete();
}
}
On expectNext it fails coz it returns 0 and not 1.
mongoTemplate.estimatedCount returns 0
When I test the repository from Postman (repo is calling inside service), it creates the document in MongoDB wil ttl index, as expected.
In test fonfig I have set the ${ttl.index} to 20.
What am I doing wrong?
I don't know if it is to late, but I had the same problem today.
I Found your question looking for an answer for my problem hahahaha.
This snipped worked for me:
#Container
public static MongoDBContainer container = new MongoDBContainer(DockerImageName.parse("mongo:6"));
#DynamicPropertySource
static void mongoDbProperties(DynamicPropertyRegistry registry) {
registry.add("spring.data.mongodb.uri", container::getReplicaSetUrl);
}
#Bean
public ReactiveMongoTemplate reactiveMongoTemplate() throws Exception {
container.start();
ConnectionString connectionString = new ConnectionString(container.getReplicaSetUrl());
MongoClientSettings mongoClientSettings = MongoClientSettings.builder()
.applyConnectionString(connectionString)
.build();
MongoClient mongoClient = MongoClients.create(mongoClientSettings);
return new ReactiveMongoTemplate(mongoClient,"test");
}
Apparently ReactiveMongoTemplate is not being injected by default, then I created my own Bean an it worked
How to write unit test (via Junit) for MongoTemplate updateFirst() method ?
I have this service class:
#Service
public class TemplateServiceImpl implements TemplateService
{
#Resource
private TemplateRepository templateRepository;
#Resource
private MongoTemplate mongoTemplate;
#Override
public TemplateDto create(TemplateDto templateDto)
{
TemplateDto result;
templateDto.setDeleted(false);
result = templateRepository.insert(templateDto);
return result;
}
#Override
public boolean update(ObjectId id, TemplateDto templateDto)
{
if (templateDto != null)
{
Update update = new Update();
if (templateDto.getName() != null)
{
update.set("name", templateDto.getName());
}
if (templateDto.getTemplate() != null)
{
update.set("template", templateDto.getTemplate());
}
if (templateDto.isDeleted())
{
update.set("deleted", Boolean.TRUE);
}
update.set("lastUpdate", new Date());
return mongoTemplate.updateFirst(new Query(Criteria.where("_id").is(id)), update, "template")
.wasAcknowledged();
}
return false;
}
}
I want write unit test for update method .
This is my relevant test class:
#ExtendWith(MockitoExtension.class)
class TemplateServiceImplTest
{
#InjectMocks
private static TemplateServiceImpl templateService;
#Mock
private static TemplateRepository templateRepository;
#Mock
private static MongoTemplate mongoTemplate;
private static TemplateDto templateDto;
private static List<TemplateDto> listOfTemplates;
private static String requestBody;
#BeforeAll
private static void setUp(){
templateDto = createTemplateDto();
listOfTemplates = createListOfTemplate();
requestBody = createRequesyBody();
}
#Test
void create()
{
when(templateRepository.insert(templateDto)).thenReturn(templateDto);
TemplateDto actualResult = templateService.create(TemplateServiceImplTest.templateDto);
assertThat(actualResult).isNotNull();
assertThat(actualResult).isInstanceOf(TemplateDto.class);
assertThat(actualResult.getId()).isEqualTo(templateDto.getId());
}
#Test
void update()
{
Update update = new Update();
/*
when(mongoTemplate.updateFirst(new Query(Criteria.where("_id").is(templateDto.getId().toString())) ,update , TemplateDto.class)).thenReturn(
UpdateResult.acknowledged());
*/
/*
given(mongoTemplate.updateFirst(new Query(Criteria.where("_id").is(templateDto.getId().toString())) ,update , TemplateDto.class));
*/
boolean actualResult = templateService.update(templateDto.getId(), templateDto);
assertThat(actualResult).isNotNull();
assertThat(actualResult).isTrue();
}
// other methods...
}
I mocked MongoTemplate like this:
#Mock
private static MongoTemplate mongoTemplate;
when I run test I get NPE for mongoTemplate at update method , I searched and I saw this 2 approach:
when(mongoTemplate.updateFirst(new Query(Criteria.where("_id").is(templateDto.getId().toString())) ,update , TemplateDto.class)).thenReturn(
UpdateResult.acknowledged());
// Or
given(mongoTemplate.updateFirst(new Query(Criteria.where("_id").is(templateDto.getId().toString())) ,update , TemplateDto.class));
But None of them worked! .
Thank you all .
Note: I already look at and tried some approaches on SO e.g. How to test Spring's declarative caching support on Spring Data repositories?, but as most of them old, I cannot make them work properly and I need a solution with the latest library versions. So, I would be appreciated if you have a look at the question and help.
#Service
#EnableCaching
#RequiredArgsConstructor
public class DemoServiceImpl implements DemoService {
private static final String CACHE_NAME = "demoCache";
private final LabelRepository labelRepository;
private final LabelTranslatableRepository translatableRepository;
private final LanguageService languageService;
#Override
public LabelDTO findByUuid(UUID uuid) {
final Label label = labelRepository.findByUuid(uuid)
.orElseThrow(() -> new EntityNotFoundException("Not found."));
final List<LabelTranslatable> translatableList = translatableRepository.findAllByEntityUuid(uuid);
return new LabelDTO(Pair.of(label.getUuid(), label.getKey()), translatableList);
}
}
I created the following Unit Test to test caching for the nethod above:
#EnableCaching
#ImportAutoConfiguration(classes = {
CacheAutoConfiguration.class,
RedisAutoConfiguration.class
})
#ExtendWith(MockitoExtension.class)
class TextLabelServiceImpl_deneme_Test {
#Autowired
private CacheManager cacheManager;
#InjectMocks
private LabelService labelService;
#Mock
private LabelRepository labelRepository;
#Mock
private LabelTranslatableRepository translatableRepository;
#Test
void test_Cache() {
UUID uuid = UUID.randomUUID();
final TextLabel textLabel = new TextLabel();
textLabel.setId(1);
textLabel.setKey("key1");
TextLabelTranslatable textLabelTranslatable = new TextLabelTranslatable();
textLabelTranslatable.setEntityUuid(uuid);
textLabelTranslatable.setLanguage(SupportedLanguage.fr);
textLabelTranslatable.setValue("value1");
final List<TextLabelTranslatable> translatableList = new ArrayList<>();
translatableList.add(textLabelTranslatable);
when(labelRepository.findByUuid(uuid)).thenReturn(Optional.of(textLabel));
when(translatableRepository.findAllByEntityUuid(uuid)).thenReturn(translatableList);
TextLabelDTO result1 = labelService.findByUuid(uuid);
TextLabelDTO result2 = labelService.findByUuid(uuid);
assertEquals(result1, result2);
Mockito.verify(translatableRepository, Mockito.times(1)).findAllByEntityUuid(uuid);
}
I am not sure if there is a missing part in my test, but at the last line (Mockito.verify()), it returns 2 instead of 1 that means caching not works. But it is working properly and there is a problem in my test I think. How should I complete the unit test to check the caching properly?
You need to annotate the service class method with #Cacheable. Try to follow the code in this tutorial. The following test code works as expected
#Import({CacheConfig.class, DemoServiceImpl.class})
#ExtendWith(SpringExtension.class)
#EnableCaching
#ImportAutoConfiguration(classes = {
CacheAutoConfiguration.class,
RedisAutoConfiguration.class
})
class DemoServiceImplTest {
#MockBean
private LabelRepository labelRepository;
#Autowired
private DemoServiceImpl demoService;
#Autowired
private CacheManager cacheManager;
#TestConfiguration
static class EmbeddedRedisConfiguration {
private final RedisServer redisServer;
public EmbeddedRedisConfiguration() {
this.redisServer = new RedisServer();
}
#PostConstruct
public void startRedis() {
redisServer.start();
}
#PreDestroy
public void stopRedis() {
this.redisServer.stop();
}
}
#Test
void givenRedisCaching_whenFindItemById_thenItemReturnedFromCache() {
UUID id = UUID.randomUUID();
Label aLabel = new Label(id, "label");
Mockito.when(labelRepository.findById(id)).thenReturn(Optional.of(aLabel));
Label labelCacheMiss = demoService.findByUuid(id);
Label labelCacheHit = demoService.findByUuid(id);
Mockito.verify(labelRepository, Mockito.times(1)).findById(id);
}
}
With this service class code:
#Service
#RequiredArgsConstructor
#EnableCaching
public class DemoServiceImpl {
public static final String CACHE_NAME = "demoCache";
private final LabelRepository labelRepository;
#Cacheable(value = CACHE_NAME)
public Label findByUuid(UUID uuid) {
return labelRepository.findById(uuid)
.orElseThrow(() -> new EntityNotFoundException("Not found."));
}
}
And this CacheConfig:
#Configuration
public class CacheConfig {
#Bean
public RedisCacheManagerBuilderCustomizer redisCacheManagerBuilderCustomizer() {
return (builder) -> builder
.withCacheConfiguration(DemoServiceImpl.CACHE_NAME,
RedisCacheConfiguration.defaultCacheConfig().entryTtl(Duration.ofMinutes(10)));
}
#Bean
public RedisCacheConfiguration cacheConfiguration() {
return RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofMinutes(60))
.disableCachingNullValues()
.serializeValuesWith(
RedisSerializationContext.SerializationPair.fromSerializer(
new GenericJackson2JsonRedisSerializer()));
}
}
I have a service class, that executes user's request:
public class UnitServiceImpl extends HttpRequestServiceImpl implements UnitService {
private final UnitRepository unitRepository;
public UnitServiceImpl(UnitRepository unitRepository) {
this.unitRepository = unitRepository;
}
#Override
public Unit addUnit(String unitName) {
final Unit unit = new Unit();
unit.setUnitName(unitName);
return unitRepository.save(unit);
}
#Override
public Unit getUnit(int id) {
final Unit unit = unitRepository.findById(id);
if (unit == null) {
throw new EntityNotFoundException("Unit is not found");
}
return unit;
}
#Override
public Unit updateUnit(int id, String unitName) {
final Unit unit = getUnit(id);
unit.setUnitName(unitName);
return unitRepository.save(unit);
}
#Override
public Iterable<Unit> getAllUnits() {
return unitRepository.findAll();
}
}
Controller, that's use Service:
#RestController
public class UnitController {
private final UnitService managementService;
public UnitController(UnitService managementService) {
this.managementService = managementService;
}
#GetMapping(value = "/unit", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Iterable<Unit>> getAllUnits() {
final Iterable<Unit> allUnits = managementService.getAllUnits();
return new ResponseEntity<>(allUnits, HttpStatus.OK);
}
#PostMapping(value = "/unit", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Unit> addUnit(HttpServletRequest request) throws FieldsIsAbsentException {
final String unitName = managementService.getParameter(request, "unit_name");
final Unit unit = managementService.addUnit(unitName);
return new ResponseEntity<>(unit, HttpStatus.CREATED);
}
#GetMapping(value = "/unit/{id}", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Unit> getUnitById(#PathVariable("id") int id) {
final Unit unit = managementService.getUnit(id);
return new ResponseEntity<>(unit, HttpStatus.OK);
}
#PutMapping(value = "/unit/{id}", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Unit> updateUnit(HttpServletRequest request, #PathVariable("id") int id) {
final String unitName = managementService.getParameter(request, "unit_name");
return new ResponseEntity<>(managementService.updateUnit(id, unitName), HttpStatus.ACCEPTED);
}
}
I created unit tests. They are mockito methods isn't working. All test methods doing request to database. Test class:
#SpringBootTest
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(classes = ApplicationTestConfig.class)
#WebAppConfiguration
#AutoConfigureMockMvc
class UnitControllerTest {
#Autowired
private MockMvc mockMvc;
#Mock
UnitService unitService;
#Autowired
private UnitController unitController;
private final List<Unit> units = new ArrayList<>();
#BeforeEach
public void initUnits() {
this.mockMvc = MockMvcBuilders.standaloneSetup(unitController)
.setControllerAdvice(new ExceptionHandlingController()).build();
Unit unit = new Unit();
unit.setUnitName("someUnit 1");
unit.setId(1);
units.add(unit);
unit = new Unit();
unit.setId(2);
unit.setUnitName("Some unit 2");
units.add(unit);
}
#Test
void testGetAllUnits() throws Exception {
when(this.unitService.getAllUnits()).thenReturn(units);
mockMvc.perform(get("/unit"))
.andDo(print())
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON));
}
#Test
void testUnitNotFound() throws Exception {
int id = -1;
given(this.unitService.getUnit(id)).willThrow(EntityNotFoundException.class);
mockMvc.perform(get("/unit/" + id))
.andDo(print())
.andExpect(status().isNotFound())
.andExpect(content().contentType(MediaType.APPLICATION_JSON));
}
#Test
void testUnitFound() throws Exception {
int id = 5;
Unit unitWithName = new Unit();
unitWithName.setId(id);
unitWithName.setUnitName("NameUnit");
given(unitService.getUnit(id)).willReturn(unitWithName);
mockMvc.perform(get("/unit/" + id).contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(jsonPath("$.id").value(id))
.andExpect(jsonPath("$.unitName").value(unitWithName.getUnitName()));
}
#Test
void testAddUnit() throws Exception {
Unit unit = new Unit();
unit.setId(1);
unit.setUnitName("TestUnit");
given(unitService.addUnit("TestUnit")).willReturn(unit);
mockMvc.perform(post("/unit").param("unit_name", "TestUnit"))
.andExpect(status().isCreated())
.andExpect(jsonPath("$.unitName").value(unit.getUnitName()))
.andExpect(jsonPath("$.id").value(1));
}
}
This code is trying to read or write to database. I've tried so many variants.
I've been trying to write tests for a few days.=( What is the error?
I've changed my test class onto next code and it works now:
#WebMvcTest(UnitController.class)
class UnitControllerTest {
#Autowired
private MockMvc mockMvc;
#MockBean
UnitService unitService;
private final List<Unit> units = new ArrayList<>();
#BeforeEach
public void initUnits() {
Unit unit = new Unit();
unit.setUnitName("someUnit 1");
unit.setId(1);
units.add(unit);
unit = new Unit();
unit.setId(2);
unit.setUnitName("Some unit 2");
units.add(unit);
}
///test methods
I've been writting some tests for a legacy web app on java using DeltaSpike, Weld, Hibernate and others frameworks.
I have faced some problem with my first test class that injects many Mocked interfaces on a Service.
Let me show some code:
Service to be tested
public class DistribuicaoProcessoManualServiceImpl extends DistribuicaoService implements DistribuicaoProcessoManualService {
#Inject
#WebServiceTJDBEntityManager EntityManager wstjEM;
private ForoTJComarcaMPRepository foroMPRepository;
private AssuntoTJNaturezaMPRepository naturezaMPRepository;
private VaraTJVaraMPRepository varaMPRepository;
private ClasseTJTipoMPRepository tipoMPRepository;
private ProcessoRepository processoRepository;
private UsuarioRepository usuarioRepository;
private UsuarioDaSessao usuarioDaSessao;
/**
* #deprecated CDI eyes only
*/
public DistribuicaoProcessoManualServiceImpl() {
this(null, null, null, null, null, null, null);
}
#Inject
public DistribuicaoProcessoManualServiceImpl(
ForoTJComarcaMPRepository foroMPRepository,
AssuntoTJNaturezaMPRepository naturezaMPRepository,
ClasseTJTipoMPRepository tipoMPRepository,
ProcessoRepository processoRepository,
UsuarioRepository usuarioRepository,
UsuarioDaSessao usuarioDaSessao,
VaraTJVaraMPRepository varaMPRepository) {
this.foroMPRepository = foroMPRepository;
this.naturezaMPRepository = naturezaMPRepository;
this.tipoMPRepository = tipoMPRepository;
this.processoRepository = processoRepository;
this.usuarioRepository = usuarioRepository;
this.usuarioDaSessao = usuarioDaSessao;
this.varaMPRepository = varaMPRepository;
}
#Override
#Transactional(readOnly = false, qualifier = {WebServiceTJDBEntityManager.class})
public Processo vinculaOuPreparaParaEspecializacao(Processo processo) {
//Service do some validations here with Guava's Preconditions;
Usuario usuario = usuarioRepository.procurarPorLogin(usuarioDaSessao.getUsuario().getLogin());
processo.atualizaInformacoesDeProcuradoriaEUsuario(usuario);
ProcessoDoTJMapeamentoParaMP processoDePara = compoeMapeamento(processo);
VaraTJVaraMP varaMP = varaMPRepository.procurarPorIdVaraTJForoEPorProcuradoria(processoDePara);
ForoTJComarcaMP comarcaMP = foroMPRepository.procurarPorIdForoEPorProcuradoria(processoDePara);
AssuntoTJNaturezaMP naturezaMP = naturezaMPRepository.procurarPorAssuntoEPorProcuradoria(processoDePara);
ClasseTJTipoMP tipoMP = tipoMPRepository.procurarPorCodigoEPorProcuradoria(processoDePara);
processoDePara
.comComarcaMP(comarcaMP)
.comVaraMP(varaMP)
.comNaturezaMP(naturezaMP)
.comTipoMP(tipoMP);
processoRepository.inclui(processo);
return processo;
}
}
The extended Class:
public abstract class DistribuicaoService {
public ProcessoDoTJMapeamentoParaMP compoeMapeamento(Processo processo) {
return new ProcessoDoTJMapeamentoParaMP(processo);
}
}
The mapper/builder/aggregator:
public class ProcessoDoTJMapeamentoParaMP implements Serializable {
private static final long serialVersionUID = 1L;
private final Processo processo;
public ProcessoDoTJMapeamentoParaMP(final Processo processo) {
this.processo = processo;
this.comCamaraMP( OrgaoJulgadorTJCamaraMP.semEfeito() )
.comRelatorMP( RelatorTJRelatorMP.semEfeito() )
.comOrigemMP( new OrgaoJulgadorTJOrigemMP() )
.comTipoDeRemessaMP();
}
public ProcessoDoTJMapeamentoParaMP comComarcaMP(ComarcaMP comarcaMP) {
processo.getDadosOrigem().setCodigoComarcaMP(comarcaMP.getIdComarca());
return this;
}
public ProcessoDoTJMapeamentoParaMP comVaraMP(VaraMP varaMP) {
processo.getDadosOrigem().setCodigoVaraMP(varaMP.getIdVaraMP());
return this;
}
public ProcessoDoTJMapeamentoParaMP comNaturezaMP(AssuntoTJNaturezaMP naturezaMP) {
processo.getAssuntoPrincipal().setCodigoNaturezaMP(naturezaMP.getIdNatureza());
return this;
}
public ProcessoDoTJMapeamentoParaMP comTipoMP(ClasseTJTipoMP tipoMP) {
processo.getDadosProcesso().getClasse().setCodigoTipoMP(tipoMP.getIdTipo());
return this;
}
ProcessoDoTJMapeamentoParaMP comCamaraMP(OrgaoJulgadorTJCamaraMP camaraMP) {
processo.getDadosDistribuicao().getMapeamento().setCodigoCamaraMP(camaraMP.getIdCamara());
return this;
}
ProcessoDoTJMapeamentoParaMP comRelatorMP(RelatorTJRelatorMP relatorMP) {
processo.getDadosDistribuicao().getMapeamento().setCodigoRelatorMP(relatorMP.getIdRelatorMP());
return this;
}
ProcessoDoTJMapeamentoParaMP comOrigemMP(OrgaoJulgadorTJOrigemMP origemMP) {
processo.getDadosDistribuicao().getMapeamento().setCodigoOrigemMP(origemMP.getIdOrigem());
return this;
}
ProcessoDoTJMapeamentoParaMP comTipoDeRemessaMP() {
processo.setTipoRemessa(TipoDeRemessa.fromTipoDeProcesso(this.processo.getProcessoVirtualTJ()));
return this;
}
public Procuradoria getProcuradoria() {
return processo.getProcuradoria();
}
public Integer getCodigoForoTJ() {
return processo.getDadosOrigem().getCodigoForoPrimeiraInstancia();
}
public Integer getCodigoVaraTJ() {
return processo.getDadosOrigem().getCodigoVaraPrimeiraInstancia();
}
public List<Parte> getPartes() {
return processo.getPartes();
}
public String getNomeAssuntoTJ() {
return processo.getAssuntoPrincipal().getDescricaoAssunto();
}
public Integer getCodigoClasseTJ() {
return processo.getDadosProcesso().getClasse().getCodigoClasse();
}
public String getNomeOrgaoJulgadorTJ() {
return processo.getDadosDistribuicao().getOrgaoJulgador().getNomeOrgaoJulgador();
}
public String getNomeRelatorTJ() {
return processo.getDadosDistribuicao().getRelator().getNomeRelator();
}
public Integer getIdAssuntoTJ() {
return processo.getAssuntoPrincipal().getCodigoAssunto();
}
public Movimentacao getUltimoMovimento() {
return null;
}
Class for Test:
#SuppressWarnings("deprecation")
#RunWith(MockitoJUnitRunner.class)
public class DistribuicaoProcessoManualServiceTest {
#Mock private ForoTJComarcaMPRepository foroMPRepository;
#Mock private AssuntoTJNaturezaMPRepository naturezaMPRepository;
#Mock private VaraTJVaraMPRepository varaMPRepository;
#Mock private ClasseTJTipoMPRepository tipoMPRepository;
#Mock private ProcessoRepository processoRepository;
#Mock private UsuarioRepository usuarioRepository;
#Mock private Usuario usuario;
#Mock private Procuradoria procuradoria;
#Mock private VaraTJVaraMP varaMP;
#Mock private ForoTJComarcaMP comarcaMP;
#Mock private AssuntoTJNaturezaMP naturezaMP;
#Mock private ClasseTJTipoMP tipoMP;
#Mock private UsuarioDaSessao usuarioDaSessao;
#InjectMocks
private DistribuicaoProcessoManualServiceImpl service = new DistribuicaoProcessoManualServiceImpl();
private Processo processo;
#Before
public void setUpMethod() {
initMocks(this);
//Others Builders for populate "processo" here;
processo = ProcessoBuilder()
.com(hoje)
.com(PARECER)
.com(FISICO)
.com(dadosProcesso)
.com(dadosOrigem)
.com(distribuicao)
.com(fila)
.cria();
ProcessoDoTJMapeamentoParaMP mapeamento = new ProcessoDoTJMapeamentoParaMP(processo);
when(usuario.getLogin()).thenReturn("luizrodriguesj");
when(usuario.getProcuradoria()).thenReturn(procuradoria);
when(usuarioDaSessao.getUsuario()).thenReturn(usuario);
when(usuarioRepository.procurarPorLogin(anyString())).thenReturn(usuario);
when(comarcaMP.getIdComarca()).thenReturn(1);
when(foroMPRepository.procurarPorIdForoEPorProcuradoria(mapeamento)).thenReturn(comarcaMP);
when(varaMP.getIdVaraMP()).thenReturn(1);
when(varaMPRepository.procurarPorIdVaraTJForoEPorProcuradoria(mapeamento)).thenReturn(varaMP);
when(naturezaMP.getIdNatureza()).thenReturn(1);
when(naturezaMPRepository.procurarPorAssuntoEPorProcuradoria(mapeamento)).thenReturn(naturezaMP);
when(tipoMP.getIdTipo()).thenReturn(1);
when(tipoMPRepository.procurarPorCodigoEPorProcuradoria(mapeamento)).thenReturn(tipoMP);
}
Method with problem:
#Test(expected = ApplicationException.class)
public void naoPermitirDistribuicaoDeProcessoSemUmMapeamentoDeVaraCorrespondente() {
service.vinculaOuPreparaParaEspecializacao(processo);
}
The interface that it was possible to mock:
public interface UsuarioRepository extends GenericDAO<Usuario, Long> {
boolean isAutenticavel(Usuario usuario);
Usuario procurarPorLogin(String login);
List<Usuario> lista(UsuarioPesquisa pesquisa, Paginacao paginacao);
}
One of Interfaces that not obey instruction mock and return null:
public interface ForoTJComarcaMPRepository extends GenericDAO<ForoTJComarcaMP, Long> {
ForoTJComarcaMP procurarPorIdForoEPorProcuradoria(ProcessoDoTJMapeamentoParaMP processoDePara);
List<ForoTJComarcaMP> lista(DominioMPPesquisa pesquisa, Paginacao paginacao);
ForoTJComarcaMP procuraPorForoTJ(ForoTJComarcaMP foroTJComarcaMP);
ForoTJComarcaMP procuraPorEntidade(ForoTJComarcaMP clone);
List<ForoTJComarcaMP> listaMapeamentoDistinctPor(Procuradoria procuradoria);
}
After others methods in this class that runs without any problem, this last one just fails because a NullPointerException (NPE) that occurs in:
VaraTJVaraMP varaMP = varaMPRepository.procurarPorIdVaraTJForoEPorProcuradoria(processoDePara);
AssuntoTJNaturezaMP naturezaMP = naturezaMPRepository.procurarPorAssuntoEPorProcuradoria(processoDePara);
ClasseTJTipoMP tipoMP = tipoMPRepository.procurarPorCodigoEPorProcuradoria(processoDePara);
ForoTJComarcaMP comarcaMP = foroMPRepository.procurarPorIdForoEPorProcuradoria(processoDePara);
....
// The references "comarcaMP", "varaMP", "naturezaMP", "tipoMP" are null here and next step throws a NPE.
processoDePara
.comComarcaMP(comarcaMP)
Other Mocked Interface declared work without problem, like this one:
Usuario usuario = usuarioRepository.procurarPorLogin(usuarioDaSessao.getUsuario().getLogin());
Where the "usuario" reference is setted as declared on setup method in Test Class.
Sorry for any mistake or lack of more informations.
Thanks and best regards!