Giter Club home page Giter Club logo

mongockito's Introduction

Mongockito

Java library for Mongodb repository unit testing.

Description

Currently, there is no library that allows you to build an H2-style mongodb in memory.

Starting from the premise in which the database is correctly configured, using the mockito library and based on ArgumentCaptor, we can validate that the fields sent to mongodb are the expected ones.

Prerequisites

  • Java: 17
  • Spring-boot based: 3.2.2

NOTE: There are a compile error with Java 21, but it's compatible with java 21 projects.

Installation

    <dependency>
        <groupId>io.mongockito</groupId>
        <artifactId>mongockito</artifactId>
        <version>${mongockito.version}</version>
        <scope>test</scope>
    </dependency>

Releases:

Release Date Information
1.0-SNAPSHOT 2-may-24 First release
2.0-SNAPSHOT 13-may-24 refactoring builder methods

Validations

Operation

Operation Spring Documentation
FIND find
FIND_ONE findOne
FIND_BY_ID findById
FIND_AND_REMOVE findAndRemoce
UPDATE_FIRST updateFirst
UPDATE_MULTI updateMulti
UPSERT upsert
SAVE save

ValidationType

Validation Description
EQUALS Validates that the value of a field is as expected
NOT_NULL Validates that the field is not null
NULL Validates that the field is null
COLLECTION_SIZE Validates that collection has expected number of elements
JSON Validates that the json to be inserted in the collection is equal to the input object
JSON_BY_KEY Validate that a part of json to be inserted in the collection is equal to comparable object

Alternative validations

  • There are the following types of validations
Simplified Method ValidationType
validatesEquals EQUALS
validatesNotNull NOT_NULL
validatesNull NULL
validatesCollectionSize COLLECTION_SIZE
validatesJson JSON
validatesJsonByKey JSON_BY_KEY

NOTE: all this functions can be replaced by one single function with parameters, see VerifyTest class for more examples

    // use this
    .validates(ValidationType.NULL, NULLABLE_FIELD_NAME)
    // instead of him own method
    .validatesNull(NULLABLE_FIELD_NAME)

Other configuration attributes

  • addVerificationMode:
    • Allows verifying that certain behavior happened at least once / exact number of times / never. E.g: (MockitoDoc)
  • fromCollection:
    • Optional parameter used to indicate the mongo collection name as an attribute instead of being embedded inside the entity bean using the @Document annotation.
  • addAdapter:
    • With this operation we can add gson TypeAdapter class (Gson)
  • allowSerializeNulls:
    • This parameter will indicate if the data used in the mongo operation aggregates the entity null fields

Examples:

To see a complete example, follow this documentation

  • The following example will validate MongoDB save operation of a collection item defined by identifier, and will check that the attached fields have been sent to the DB as intended.
    public static final String ID_FIELD = new ObjectId().toHexString();

    Verify.that()
        .thisOperation( Operation.SAVE )
        .ofClass( EntityExample.class )
        .validatesEquals( "_Id", ID_FIELD )
        .validatesEquals( "boolean_field", true )
        .validatesEquals( "string_field", "name" )
        .validatesNull( "one_field" )
        .validatesNotNull( "another_field" )
        .run( <mongoTemplate> );
  • This is an example to validate no field is missing on save operation
    public static final String ID_FIELD = new ObjectId().toHexString();
    public static final LocalDateTime LOCAL_DATE_TIME_NOW = LocalDateTime.now();

    // Item sent on save operation and want to check no field is missing
    final EntityExample entityExample = EntityExample.builder()
        .id( ID_FIELD )
        .month( "02" )
        .locked( Boolean.TRUE )
        .creationUser( "User_a" )
        .creationTimestamp( LOCAL_DATE_TIME_NOW )
        .lastUpdateUser( "User_b" )
        .lastUpdateTimestamp( LOCAL_DATE_TIME_NOW.plusDays( INTEGER_ONE ) )
        .entityExampleMap( createFieldMap() )
        .build();
	
    // Validation
    Verify.that()
        .thisOperation( Operation.SAVE )
        .ofClass( EntityExample.class )
        .validatesJson( EntityExample.class,  entityExample )
        .addVerificationMode(times(INTEGER_ONE))
        .run( <mongoTemplate> );
	
  • In this example we validate with specific methods for the save operation
    public static final String ID_FIELD = new ObjectId().toHexString();
    public static final LocalDateTime LOCAL_DATE_TIME_NOW = LocalDateTime.now();

    // Item sent on save operation and want to check no field is missing
    final EntityExample entityExample = EntityExample.builder()
        .id( ID_FIELD )
        .month( "02" )
        .locked( Boolean.TRUE )
        .creationUser( "User_a" )
        .creationTimestamp( LOCAL_DATE_TIME_NOW )
        .lastUpdateUser( "User_b" )
        .lastUpdateTimestamp( LOCAL_DATE_TIME_NOW.plusDays( INTEGER_ONE ) )
        .entityExampleMap( createFieldMap() )
        .build();
	
    // Validation
    Verify.that()
        .thisOperation( Operation.SAVE )
        .ofClass( EntityExample.class )
        .fromCollection( "document_collection_example_name" ) // instead of use @Document in Entity Bean
        .validatesJson(entityExample)
        .validatesJsonByKey(ENTITY_EXAMPLE_MAP, entityExample.getEntityExampleMap())
        .validatesNull(NULLABLE_VALUE_FIELD)
        .validatesNotNull(DEFAULT_KEY_ID)
        .validatesEquals(DEFAULT_KEY_ID, entityExample.getId())
        .validatesCollectionSize(ENTITY_EXAMPLE_LIST, entityExample.getEntityExampleList().size())
        .run( <mongoTemplate> );
	

mongockito's People

Contributors

mfruizs avatar

Stargazers

 avatar David Gómez avatar  avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.