Issue
How to simulate "DB down" condition for negative integration test of application ?
Have to write the negative integration test of application with mocked Db in context as follows:
@Bean
public MongoDb mongoDb() throws URISyntaxException {
return new MongoDb(new URI(String.format("mongodb://localhost:%s/", mongoDbPort)), databaseName);
}
The class MongoDb being:
public class MongoDb {
private final MongoClient mongo;
private final String databaseName;
public MongoDb(URI url, String databaseName) {
log.debug("Mongodb url:" + url);
mongo = new MongoClient(url.getHost(), url.getPort());
this.databaseName = databaseName;
}
@PreDestroy
public void shutdown() {
log.debug("Tearing down mongo.");
final MongoDatabase db = mongo.getDatabase(databaseName);
if (db != null) {
db.drop();
}
}
}
How to simulate "DB down" condition here for negative test case (with same context bean)?
Tried Stopping the mongo in my testCase: mongoDb.getMongo().dropDatabase(dbnameValue); but it didn't raise any exception
Any clue is appreciated!
Solution
There is an old post about using PowerMockito with MongoDB: Unit testing with MongoDB
The API has changed but the way of mocking should still be usable.
MongoClient mongo = PowerMockito.mock(MongoClient.class);
PowerMockito.when(mongo.getDatabase("DBDownForTest")).doThrow(new MongoClientException("Test DB is down"));
This will only work if you are calling getDatabase
with the argument DBDownForTest
. Otherwise you will have to use anyString()
.
Maybe you can even use Mockito without PowerMockito with current MongoDB versions.
Answered By - Jens Dibbern
Answer Checked By - Clifford M. (JavaFixing Volunteer)