Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save FlorinAlexandru/084cc0b190922415657f2d1dc4e341dd to your computer and use it in GitHub Desktop.
Save FlorinAlexandru/084cc0b190922415657f2d1dc4e341dd to your computer and use it in GitHub Desktop.
Integration test with Mongo database and Toxiproxy
@Testcontainers
@SpringBootTest(properties = {"spring.main.allow-bean-definition-overriding=true"})
class ToxiproxyMongoApplicationTests {
@Autowired
private PersonRepository personRepository;
private static final Network network = Network.newNetwork();
private static final DockerImageName dockerImageName = DockerImageName.parse("mongo:5.0.5")
.asCompatibleSubstituteFor("mongo");
@Container
static final MongoDBContainer mongoDbContainer = new MongoDBContainer(dockerImageName)
.withNetwork(network)
.withNetworkAliases("mongo")
.withReuse(true);
@Container
private static final ToxiproxyContainer toxiproxy = new ToxiproxyContainer("ghcr.io/shopify/toxiproxy:2.6.0")
.withNetwork(network);
private static Proxy mongoProxy;
@DynamicPropertySource
static void mongoProperties(DynamicPropertyRegistry registry) throws IOException {
ToxiproxyClient toxiproxyClient = new ToxiproxyClient(toxiproxy.getHost(), toxiproxy.getControlPort());
mongoProxy = toxiproxyClient.createProxy("mongodb", "0.0.0.0:8666", "mongo:27017");
int port = mongoDbContainer.getMappedPort(27017);
registry.add("spring.data.mongodb.host", toxiproxy::getHost);
registry.add("spring.data.mongodb.port", () -> toxiproxy.getMappedPort(8666));
}
@Test
void withLatency() throws IOException {
mongoProxy.toxics().latency("mongo-latency", ToxicDirection.DOWNSTREAM, 2600).setJitter(100);
var result = personRepository.findAll();
assertThat(result).isEmpty();
}
@Test
void withoutConnection() throws IOException {
var result = personRepository.findAll();
assertThat(result).isEmpty();
mongoProxy.disable();
assertThatThrownBy(() -> personRepository.findAll()).isInstanceOf(DataAccessResourceFailureException.class);
mongoProxy.enable();
result = personRepository.findAll();
assertThat(result).isEmpty();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment