public static void assertDuplicateKeyException(Throwable exception) {
    Preconditions.checkNotNull(exception, "exception");

    // unwrap, if necessary
    exception = exception instanceof MongoException ? exception : exception.getCause();

    // fongo throws directly DuplicateKeyException
    if (exception instanceof DuplicateKeyException) return;

    // MongoDB throws custom exception
    if (exception instanceof MongoCommandException) {
      String codeName = ((MongoCommandException) exception).getResponse().get("codeName").asString().getValue();
      int errorCode = ((MongoCommandException) exception).getErrorCode();

      check(codeName).is("DuplicateKey");
      check(errorCode).is(11000); // code 11000 stands for DuplicateKeyException

      // all good here (can return)
      return;
    }

    // for bulk writes as well
    if (exception instanceof MongoBulkWriteException) {
      List<BulkWriteError> errors = ((MongoBulkWriteException) exception).getWriteErrors();
      check(errors).hasSize(1);
      check(errors.get(0).getCode()).is(11000);
      check(errors.get(0).getMessage()).contains("duplicate key");
      return;
    }

    // if we got here means there is a problem (no duplicate key exception)
    fail("Should get duplicate key exception after " + exception);
  }
Ensures current exception has been generated due to a duplicate (primary) key.
Differentiates between Fongo and Mongo exceptions since the behaviour under these databases
is different.
mongo/test/org/immutables/mongo/fixture/MongoAsserts.java