concept test in category microservice

This is an excerpt from Manning's book Bootstrapping Microservices with Docker, Kubernetes and Terraform.
What’s this npx command that’s suddenly appeared? This is a very useful command that comes with Node.js and allows us to run installed dependencies from the command line. Before npx was added to Node.js, we used to install modules like Nodemon globally. Now we run tools like this directly from the current project’s dependencies. This really helps us use the right versions of modules and stops our system from getting cluttered up by globally installed modules.
Automated testing, put simply, is code-driven testing. We write code to exercise our code and verify that it works correctly. This sounds like circular logic, but we break out of it after a single iteration. We have our application code or code under test and then we have our test code (or just tests).
Often the test code directly invokes the code under test, but it can also be invoked indirectly such as through HTTP requests or RabbitMQ messages. The test code then verifies that the result is correct, either by checking the output or checking the behaviour.
In chapter 2 we introduced the idea of adding npm scripts to our package.json file so that we can use the conventional npm commands like npm start. In chapter 2 we configured the start script, here we’ll do the same for the test script.
Once we have configure package.json for this we’ll be able run our test suite as follows:
npm test

This is an excerpt from Manning's book Testing Microservices with Mountebank.
This setup also makes testing—the focus of this book—easier. Most of the tests can be in process, and, assuming you are using dependency injection, you can test pieces in isolation using mocking libraries. Black-box testing the application only requires you to coordinate the application deployment with the database schema version. Test data management comes down to loading the database with a set of sample test data. You can easily solve all of these problems.
The simplest approach is to mirror what mocking libraries do: directly collude with the mocked objects. The unit testing community often speaks about the 3A pattern, which is to say that each test has three components: arrange, act, and assert. First you set up the data needed for the test to run (arrange), then you execute the system under test (act), and finally you assert that you got the expected response (figure 1.10). Service virtualization can support this approach through an API that lets you configure the virtual service dynamically.
This approach supports creating a laboratory environment for each test, in order to strictly control the inputs and dependencies of the service under test. However, it does make a couple of fundamental assumptions. First, it expects each test to start with a clean slate, which means that each test must remove the test data it added to prevent that data from interfering with subsequent tests. Second, the approach doesn’t work if multiple tests are run in parallel. Both of these assumptions fit nicely into automated behavioral tests, as test runners typically ensure tests are run serially. As long as each developer runs their own virtual service, you can avoid the resource contention that comes with concurrent test runs.

This is an excerpt from Manning's book Testing Java Microservices: Using Arquillian, Hoverfly, AssertJ, JUnit, Selenium, and Mockito.
This example tells Arquillian to use WildFly 9.0.0 in managed mode. When running a test, Chameleon checks whether the configured container is installed; if it isn’t, Chameleon downloads and installs it. Then, Chameleon registers the required underlying adapter on the classpath. After that, the container is started, and the test is executed normally.
Listing 4.12. Using a WireMock interceptor in a test
@RunWith(Arquillian.class) public class ArquillianRemoteTest extends ArquillianAbstractTest { #1 @Deployment #2 public static WebArchive createDeployment() { return createBaseDeployment(ArquillianRemoteTest.class .getName()).addClass(ArquillianRemoteTest.class) .addClass(ArquillianAbstractTest.class) .addAsLibrary(Maven.resolver().resolve("com.github" + ".tomakehurst:wiremock-standalone:2.2.1") .withoutTransitivity().asSingleFile()); } @Inject #3 private IgdbGateway gateway; @Test #4 public void testSearchGames() throws Exception { Assert.assertNotNull(this.gateway); final JsonArray json = gateway.searchGames("The Legend of " + "Zelda: Breath of the Wild"); Assert.assertNotNull(json); final JsonObject game = json.getJsonObject(0); Assert.assertEquals("Unexpected id", 7346, game .getJsonNumber("id").intValue()); Assert.assertEquals("Unexpected name", "The Legend of " + "Zelda: Breath of the Wild", game.getString("name")); } }
It’s possible to add all sorts of undefined magical plugins to the build scripts to ensure that these runtime dependencies are started. This is not recommended, because the test would no longer be self-contained and couldn’t be run by IDEs out of the box.
The neat libraries in listing 7.4 enable your test to fire up a MongoDB instance and a Redis instance directly in the test with relatively little overhead. Due to the lifecycle management of the JUnit test as a whole, @BeforeClass usually isn’t early enough to bootstrap these requirements. Implementing JUnit rules allows you to include them deeper in the test lifecycle. Variables in the rules are used to keep a reference to the process, so that you can clean up after the test is complete. The libraries used in the rules you’ll define in a moment will download and initialize the MongoDB and Redis instances for you. You don’t have to manually prepare anything, and your tests remain self-contained.
If possible, build a deployment starting with a ShrinkWrap of the WAR file for the microservice. Then add the provided scoped artifacts to the mix of dependencies that the microservice requires. This means the test is as close as possible to a real production deployment.

This is an excerpt from Manning's book Microservices in .NET Core: with examples in Nancy.
Nancy applications are testable. Nancy itself is built in a test-driven fashion. Likewise, Nancy allows an easy test-driven-development flow for writing Nancy applications. Not only are Nancy’s APIs designed with testability in mind, but Nancy also comes with a companion library (Nancy.Testing) specifically aimed at making it easy to write tests for Nancy applications.
The test pyramid shown in figure 7.1 is a tool you can use to guide which kinds of tests you should write and how many you should have of each kind. You can find variations of the test pyramid in different writings; all of them put tests on different levels, where the levels at the top of the pyramid are broad in scope and the tests at the bottom are narrow. The test pyramid illustrates that you should aim for having many narrowly focused tests (the ones at the wide bottom of the pyramid) and only a few broadly scoped tests (the ones at the narrow top).
The tests at the bottom of the test pyramid also deal with a single microservice, but these tests don’t work over HTTP and don’t deal with the entire microservice. These unit tests interact with the parts of the microservice under test directly and in memory. To call the endpoints implemented in your Nancy modules, you’ll use the Nancy.Testing library that comes as a companion library alongside Nancy. Nancy.Testing lets you write tests that make calls to Nancy endpoints in memory. The calls go through Nancy in exactly the same way HTTP requests would, but without going through the network stack. To the code in your Nancy modules, calls made with Nancy.Testing look exactly like real HTTP requests.
At the unit-test level, I’ll show you two kinds of tests (see figure 7.4): one that uses a database and one that uses a mock in place of the database. I consider both to be unit tests, even though the first type uses a database. Two things make a test a unit test: its scope is a small piece of functionality, and the test code and the production code in the microservice run in the same process.
Figure 7.4. At the unit-test level, there are two kinds of tests: those that use a database and those that don’t.
![]()
The narrow scope of a unit test makes it precise: when it fails, the problem lies in a small amount of code. A narrow scope also enables you to write tests that cover failure scenarios properly. Both types of unit tests are faster than service-level tests, but of course the tests that mock out databases are faster than those that use a database. Therefore, you can have both and will probably have more tests that mock the database than tests that don’t.
Sometimes you may also have even narrower unit tests that test the business logic in the microservices directly by instantiating domain objects and testing them directly. I take a pragmatic approach to deciding how narrow the narrowest unit tests should be: I use a test-first workflow that starts from the outside, with tests that use Nancy.Testing making calls to endpoint handlers in Nancy modules. I start with tests that cover the broad strokes of what the endpoint should do, an then I progressively add tests for more details. Only when it becomes awkward to test a particular detail through the endpoint handler do I begin to write narrower unit tests. For instance, covering a particular case in the business logic with tests that call through the endpoint handler might require a lot of setup code. That’s a signal to switch down to a test that has a narrower scope: just those cases in the business logic. I’ll write tests for those cases that work directly on the classes that should implement that particular part of the business logic.
For the Loyalty Program microservice, you need unit tests that test the endpoint that lets you create users with a number of different inputs covering both possible valid inputs and invalid inputs. Likewise, you need tests that try to read both existing and nonexistent users from the query endpoint that lets you read users. You need similar tests for the other endpoints in the microservice. Loyalty Program is sufficiently simple that you don’t need to switch down to tests that are narrower than the microservice’s endpoints. So, the units tests I’ll show you later all work by calling endpoint handlers through Nancy.Testing.
Finally, you’re ready to write the test. It has three steps:
You can run the test in PowerShell with dotnet:
PS> dotnet testThis will open two command windows: one with each of the processes in the Loyalty Program microservice. The test runs, and, when it finishes, the two windows are closed. The output from xUnit is as follows:
Discovering: LoyaltyProgramIntegrationTest Discovered: LoyaltyProgramIntegrationTest Starting: LoyaltyProgramIntegrationTest LoyaltyProgramIntegrationTests.RegisterUserAndGetNotification.Scenario Finished: LoyaltyProgramIntegrationTest === TEST EXECUTION SUMMARY === LoyaltyProgramIntegrationTest Total: 1, Errors: 0, Failed: 0, Skipped: 0, Time: 12.563sThis test is slow, and you had to do some setup before you were ready to write it. This is why such tests are higher on the test pyramid than the unit tests you wrote earlier. You should have only a few of this kind of test, whereas you can have many unit tests.