mercredi 17 juin 2020

How test a method with @Transactional annotation with a mongoDb

how can i test a method with the @Transaction annotation. I wrote a method which works if i test it when the application is running (manually). But my test for this doesn't work. My goal is to write a test which make sure that my transaction method works when a exception happened, so nothing is stored in the DB.

Setting

  • java: 11
  • springboot : 2.3.1
  • mongodb : 4.2.7

application.yml

spring:
 data:
    mongodb:
      uri: mongodb://okAdmin:test@mongo_one:27017,mongo_two:27018,mongo_three:27019/?replicaSet=rs0
      database: "ok"
      auto-index-creation: false

Mongo configuration for spring

@Configuration
public class MongoTransactionConfig extends AbstractMongoClientConfiguration {

    @Value("${spring.data.mongodb.database}")
    private String database;
    @Value("${spring.data.mongodb.uri}")
    private String mongo_uri;

    @Bean
    MongoTransactionManager transactionManager(MongoDatabaseFactory mongoDatabaseFactory) {
        return new MongoTransactionManager(mongoDatabaseFactory);
    }

    @Bean
    public MongoClient mongoClient() {
        return MongoClients.create(mongo_uri);
    }

    @Override
    protected String getDatabaseName() {
        return database;
    }
}

Method

@Slf4j
@Service
public class CompanyService {


    public static final int MIN_NUMBER_OF_BRANCHES = 1;
    private final CompanyRepository companyRepository;

    @Autowired
    public CompanyService(@NonNull CompanyRepository companyRepository) {
        this.companyRepository = companyRepository;
    }


    //  TODO : TEST
    @Transactional // (rollbackFor = {StoreException.class}) => NOT WORKING FOR TESTS/NO CATCHING
    public void addBranch(@NonNull Branch branch) throws IllegalAccessError, StoreException {
        log.debug("Service: Add branch to company");
        long companyId = branch.getCompanyId();
        companyRepository.addBranch(branch);
        long branches_number = companyRepository.countBranchesForCompany(companyId);
        if (branches_number == MIN_NUMBER_OF_BRANCHES) {
            companyRepository.setSignupCompleted(companyId, true);
        }

    }
}

Test

@SpringBootTest(properties = {
        "spring.data.mongodb.database=ok_test"
})
//@Transactional
class CompanyServiceMongoTest {
    private final String COLLECTION_BRANCHES = "branches";

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private CompanyService testObject;

    @Autowired
    private CompanyRepository companyRepository;


    @Test
    void addBranch_test_transaction_company_not_saved(){
        // PREPARE
        Branch branchTestDummy = BranchTest.createBranchTestDummy();
        Query branchQuery = new Query();
        branchQuery.addCriteria(Criteria.where("company_id").is(branchTestDummy.getCompanyId()));
        // ACTION
        assertThrows(StoreException.class, ()-> testObject.addBranch(branchTestDummy));
        // CHECK
        boolean exists = mongoTemplate.exists(branchQuery, BranchDao.class, COLLECTION_BRANCHES);
        assertFalse(exists);
    }
}

Run console output

2020-06-17 11:12:34.635  INFO 182967 --- [mongo_two:27017] org.mongodb.driver.connection            : Opened connection [connectionId{localValue:1426609, serverValue:1511263}] to mongo_two:27017
2020-06-17 11:12:34.635 DEBUG 182967 --- [mongo_two:27017] org.mongodb.driver.cluster               : Checking status of mongo_two:27017
2020-06-17 11:12:34.635 DEBUG 182967 --- [mongo_two:27017] org.mongodb.driver.protocol.command      : Sending command '{"ismaster": 1, "$db": "admin", "$clusterTime": {"clusterTime": {"$timestamp": {"t": 1592385154, "i": 1}}, "signature": {"hash": {"$binary": {"base64": "2Qn1NUq/OPeFI3jd2aPIoloM/x0=", "subType": "00"}}, "keyId": 6837089852169650179}}}' with request id 2853624 to database admin on connection [connectionId{localValue:1426609, serverValue:1511263}] to server mongo_two:27017
2020-06-17 11:12:34.635 DEBUG 182967 --- [mongo_two:27017] org.mongodb.driver.protocol.command      : Execution of command with request id 2853624 completed successfully in 0.32 ms on connection [connectionId{localValue:1426609, serverValue:1511263}] to server mongo_two:27017
2020-06-17 11:12:34.636  INFO 182967 --- [mongo_two:27017] org.mongodb.driver.cluster               : Monitor thread successfully connected to server with description ServerDescription{address=mongo_two:27017, type=REPLICA_SET_PRIMARY, state=CONNECTED, ok=true, minWireVersion=0, maxWireVersion=8, maxDocumentSize=16777216, logicalSessionTimeoutMinutes=30, roundTripTimeNanos=403948, setName='rs0', canonicalAddress=mongo_one:27017, hosts=[mongo_one:27017], passives=[mongo_two:27017, mongo_three:27017], arbiters=[], primary='mongo_one:27017', tagSet=TagSet{[]}, electionId=7fffffff0000000000000009, setVersion=1, lastWriteDate=Wed Jun 17 11:12:34 CEST 2020, lastUpdateTimeNanos=9570708142930}
2020-06-17 11:12:34.636  INFO 182967 --- [mongo_two:27017] org.mongodb.driver.cluster               : Adding discovered server mongo_three:27017 to client view of cluster
2020-06-17 11:12:34.636  INFO 182967 --- [mongo_two:27017] org.mongodb.driver.cluster               : Canonical address mongo_one:27017 does not match server address.  Removing mongo_two:27017 from client view of cluster
2020-06-17 11:12:34.636 DEBUG 182967 --- [mongo_two:27017] org.mongodb.driver.cluster               : Updating cluster description to  {type=REPLICA_SET, servers=[{address=mongo_one:27017, type=REPLICA_SET_PRIMARY, roundTripTime=0.6 ms, state=CONNECTED}, {address=mongo_three:27017, type=UNKNOWN, state=CONNECTING}]
2020-06-17 11:12:34.636 DEBUG 182967 --- [mongo_two:27017] org.mongodb.driver.connection            : Closing connection connectionId{localValue:1426609, serverValue:1511263}
2020-06-17 11:12:34.637  INFO 182967 --- [ngo_three:27017] org.mongodb.driver.connection            : Opened connection [connectionId{localValue:1426610, serverValue:1511264}] to mongo_three:27017
2020-06-17 11:12:34.637 DEBUG 182967 --- [ngo_three:27017] org.mongodb.driver.cluster               : Checking status of mongo_three:27017
2020-06-17 11:12:34.637 DEBUG 182967 --- [ngo_three:27017] org.mongodb.driver.protocol.command      : Sending command '{"ismaster": 1, "$db": "admin", "$clusterTime": {"clusterTime": {"$timestamp": {"t": 1592385154, "i": 1}}, "signature": {"hash": {"$binary": {"base64": "2Qn1NUq/OPeFI3jd2aPIoloM/x0=", "subType": "00"}}, "keyId": 6837089852169650179}}}' with request id 2853626 to database admin on connection [connectionId{localValue:1426610, serverValue:1511264}] to server mongo_three:27017
2020-06-17 11:12:34.637 DEBUG 182967 --- [ngo_three:27017] org.mongodb.driver.protocol.command      : Execution of command with request id 2853626 completed successfully in 0.36 ms on connection [connectionId{localValue:1426610, serverValue:1511264}] to server mongo_three:27017
2020-06-17 11:12:34.637  INFO 182967 --- [ngo_three:27017] org.mongodb.driver.cluster               : Monitor thread successfully connected to server with description ServerDescription{address=mongo_three:27017, type=REPLICA_SET_PRIMARY, state=CONNECTED, ok=true, minWireVersion=0, maxWireVersion=8, maxDocumentSize=16777216, logicalSessionTimeoutMinutes=30, roundTripTimeNanos=457039, setName='rs0', canonicalAddress=mongo_one:27017, hosts=[mongo_one:27017], passives=[mongo_two:27017, mongo_three:27017], arbiters=[], primary='mongo_one:27017', tagSet=TagSet{[]}, electionId=7fffffff0000000000000009, setVersion=1, lastWriteDate=Wed Jun 17 11:12:34 CEST 2020, lastUpdateTimeNanos=9570709659086}
2020-06-17 11:12:34.637  INFO 182967 --- [ngo_three:27017] org.mongodb.driver.cluster               : Adding discovered server mongo_two:27017 to client view of cluster
2020-06-17 11:12:34.637  INFO 182967 --- [ngo_three:27017] org.mongodb.driver.cluster               : Canonical address mongo_one:27017 does not match server address.  Removing mongo_three:27017 from client view of cluster
2020-06-17 11:12:34.637 DEBUG 182967 --- [ngo_three:27017] org.mongodb.driver.cluster               : Updating cluster description to  {type=REPLICA_SET, servers=[{address=mongo_one:27017, type=REPLICA_SET_PRIMARY, roundTripTime=0.6 ms, state=CONNECTED}, {address=mongo_two:27017, type=UNKNOWN, state=CONNECTING}]
2020-06-17 11:12:34.637 DEBUG 182967 --- [ngo_three:27017] org.mongodb.driver.connection            : Closing connection connectionId{localValue:1426610, serverValue:1511264}

THANK YOU FOR YOUR HELP

Aucun commentaire:

Enregistrer un commentaire