BlockHound allowBlocking not working with junit5 - spring-webflux

I am using blockhound to detect blocking calls, I would like to allow my custom methods but its not working and still throwing error.
i am using junit5 with blockhound-junit-platform
#BeforeAll
static void configureBlockHound(){
System.out.println("called");
BlockHound.builder().allowBlockingCallsInside(JWTHelper.class.getName(), "toToken").install();
}
When i run the test i can see called printed on console but still throwing exception.

Try to run blockhound in "log-only" mode first to understand the root cause.
BlockHound.install(builder -> builder
.blockingMethodCallback(method ->
log.error("[{}] Blocking call: {}", Thread.currentThread(), method))
);

Related

JUnit 5: execute code once before multiple tests

I'm working on a project which uses Quarkus to spin up a few REST endpoints. I have multiple integration tests which run with different test profiles or completely without a test profile. Heres an example:
#QuarkusTest
#Tag("integration")
#TestProfile(SomeProfile::class)
class IntegrationTestWithSomeProfile {
#Test
fun someTest() { ... }
}
#QuarkusTest
#Tag("integration")
class IntegrationTestWithoutProfile {
#Test
fun someTest() { ... }
}
Now I would like to execute a piece of code before the first test runs (or after the last test has finished). The problem is that #BeforeAll can only be used per class and I can't use Quarkus' start and stop events since Quarkus is started and shutdown multiple times - once for each different test profile.
Is there any hook (or hack - i don't mind dirty stuff as long as it works) which I could use, which would execute only once at the very beginning?
You can try #QuarkusTestResource with a class implementing QuarkusTestResourceLifecycleManager.
This can be used to start/stop services on the classes you want.
See: https://quarkus.io/guides/getting-started-testing#quarkus-test-resource
I finally found the solution I need. It's called TestExecutionListener. I went the route with adding a file called org.junit.platform.launcher.TestExecutionListener in resources/META-INF/services. Inside this file I've put the fqcn of my class implementing the TestExecutionListener interface.
In there I can then override testPlanExecutionStarted() and testPlanExecutionFinished(). With this, it doesn't matter how many TestProfiles we use and how many times Quarkus is started and stopped. The TestExecutionListener runs only once.

Using But keyword in BDD throws Step not implemented exception while running scenario in Quantum framework

I am trying to run a BDD scenario in Quantum framework. While execution, the step with But keyword fails with error "Step not yet implemented".
Auto-generated code snippet by QMetry Automation Framework.
TODO: remove NotYetImplementedException and call test steps
throw new NotYetImplementedException();
I do not see issue with any other BDD keywords. Only the steps starting with "But" keyword fail with the above exception. Is there anything that I am missing?
Please find the scenario we are using
Scenario: Validate help me log in link
Given user have the "XXX" app in mobile
But user open the app by the name "XXX"
Step implementation:
import cucumber.api.java.en.But;
...
#But("^user open the app by the name \"([^\"]*)\"$")
public void user_open_the_app_by_the_name(String arg1) throws Throwable {
try {
AppiumUtils.stopApp(arg1);
} catch (Exception e) {
}
}
QAF uses following BDD Keywords :
Given
When
Then
And
Using
Having
With
As But is not inbuilt keyword it may give you error. It doesn't mean that you can't use But as keyword! There is a feature to support any custom keyword(s) by defining synonyms.
You can try add following property in application.properties file:
And=But;And
This will allow you to use But as keyword and should resolve your issue.

Project running successfully using maven but failing while running with intellij

I am creating a managed object inside App.java (which is the main class of my module). I am using guice library with dropwizard framework and getting this exception only when running with IntelliJ if I run the same code with mvn it works perfectly fine which is weird and beyond my theory. So if someone has experienced something like this or have some theory behind this then please share. feel free to ask any detail.
environment.lifecycle().manage(new Managed() {
#Override
public void start() throws Exception {
}
#Override
public void stop() throws Exception {
}
});
Exception stacktrace:-
Exception in thread "main" com.google.inject.CreationException: Unable to create injector, see the following errors:
1) Injecting into inner classes is not supported. Please use a 'static' class (top-level or nested) instead of com.phonepe.growth.App$4.
at ru.vyarus.dropwizard.guice.module.installer.InstallerModule.bindExtension(InstallerModule.java:191) (via modules: ru.vyarus.dropwizard.guice.module.GuiceSupportModule -> ru.vyarus.dropwizard.guice.module.installer.InstallerModule)
1 error
at com.google.inject.internal.Errors.throwCreationExceptionIfErrorsExist(Errors.java:470)
at com.google.inject.internal.InternalInjectorCreator.initializeStatically(InternalInjectorCreator.java:155)
at com.google.inject.internal.InternalInjectorCreator.build(InternalInjectorCreator.java:107)
at com.google.inject.Guice.createInjector(Guice.java:99)
at ru.vyarus.dropwizard.guice.injector.DefaultInjectorFactory.createInjector(DefaultInjectorFactory.java:20)
at ru.vyarus.dropwizard.guice.GuiceBundle.createInjector(GuiceBundle.java:191)
at ru.vyarus.dropwizard.guice.GuiceBundle.run(GuiceBundle.java:138)
at ru.vyarus.dropwizard.guice.GuiceBundle.run(GuiceBundle.java:93)
at io.dropwizard.setup.Bootstrap.run(Bootstrap.java:200)
at io.dropwizard.cli.EnvironmentCommand.run(EnvironmentCommand.java:42)
at io.dropwizard.cli.ConfiguredCommand.run(ConfiguredCommand.java:85)
at io.dropwizard.cli.Cli.run(Cli.java:75)
at io.dropwizard.Application.run(Application.java:79)
at com.phonepe.growth.App.main(App.java:48)
This is actually a bug in guicey classpath scan (.enableAutoConfig).
Your application class is covered by a scan and so inner classes are also visible: when you start app from idea "Managed" inner class (created by the compiler for new Managed() {...}) is detected and registered as an extension which also means registration in guice context. But guice can't instantiate the inner class and throws an error.
You can enable extra diagnostic messages with .printLifecyclePhasesDetailed() (on guice bundle) and see that additional extension is indeed appear when running from idea.
Most certainly, when you run app from maven it builds into jar first and then launched. In this case, classpath scan works a bit differently and doesn't see inner classes (inside jar).. so everything works.
Please note that you don't need to instantiate and register managed object (and other common objects) manually: you can simply declare managed as a separate class and guicey will find it and properly register (both in guice and dropwizard). This is the expected way of extensions registrations, especially together with classpath scan.

How can I get junit tearDown method run if an exception is thown on startup?

I'm running selenium tests through junit.
In my system the setUp method of our AbstractSeleniumTestCase class sets up the selenium web driver and firefox profile, and the tearDown method logs out of the system and closes selenium.
Some tests will override the setUp and tearDown methods to do custom test setUp and tearDown.
The problem I'm having is that if an error accrues in the startUp method of a test (Like an unexpected popup or an selenium exception) then the web browser is never closed and the test specific tearDown operations are never done.
You could use a try block in the setUp() method to run tearDown() after encountering an error, and move the "meat" of the test setup into another method:
public void setUp() throws Exception {
try {
mySetUp();
} catch (Exception e) {
tearDown();
throw e;
}
}
Then, in your subclasses, override mySetUp() instead of setUp().
You should implement a TestWatcher and override finished method that, according to docs:
Invoked when a test method finishes (whether passing or failing)
I have not used JUnit for some time now, but as much as I remember, rules were applied before #Before.
Also you can init the driver in overriding starting method and take any relevant action by overriding the failed method etc. By that way it is possible to get rid of repetitive stuff on #Before and #After. Check the docs for specifics.
Then you can annotate your test classes with either #Rule or #ClassRule, google to understand which better suits your needs. For your any possible specific needs, it is also possible to create a rule chain.

TypeMock in an integration/regression test suite

I need to run an integration/regression test suite for our application and the application is supposed to behave differently at different times of the day. I cannot change the system time since other apps depend on it I would like to mock DateTime.Now for this purpose. However, when I put the mocking in the main method, exceptions were thrown. When I use mocking in an nunit test for the same application, it works fine. Can typemock be used only in the context of a unit test? Is there anyway I can run the solution with mocking enabled?
I ran the solution through TMockRunner.exe as well but had the same issue.
Thanks!
I see this error when I run using the method that Travis mentioned
#Travis Illig, The code for the wrapper is:
class Program
{
static void Main(string[] args)
{
ExpectationsSetup();
ConsoleApplication2.Program.Main(args);
}
public static void ExpectationsSetup()
{
Isolate.WhenCalled(() => DateTime.Now).WillReturn(new DateTime(2010, 1, 2));
}
}
I see the following error:
Unhandled Exception: TypeMock.TypeMockException:
*** No method calls found in recording block. Please check:
* Are you trying to fake a field instead of a property?
* Are you are trying to fake an unsupported mscorlib type? See supported types
here: http://www.typemock.com/mscorlib-types
at gt.a(c0 A_0, Boolean A_1)
at bg.a(Boolean A_0)
at dt.b(Boolean A_0)
at i2.b(Boolean A_0)
at i2.a(Object A_0, Boolean A_1, Func`1 A_2, Action A_3, Action A_4, Action A
_5, Boolean A_6)
at i2.b(Object A_0)
at TypeMock.ArrangeActAssert.ExpectationEngine`1.a(TResult A_0)
at ConsoleApplication2Mock.Program.ExpectationsSetup() in C:\Users\shvenkat\D
ocuments\Visual Studio 2010\Projects\ConsoleApplication2\ConsoleApplication2Mock
\Program.cs:line 22
at ConsoleApplication2Mock.Program.Main(String[] args) in C:\Users\shvenkat\D
ocuments\Visual Studio 2010\Projects\ConsoleApplication2\ConsoleApplication2Mock
\Program.cs:line 14
Any help will be appreciated
Thanks!
The typical use of Typemock Isolator is within the context of a unit test or a small testing environment. There is a non-zero level of overhead associated with running Isolator (or any other profiler-based product like NCover) in a process, so you generally don't want to do that.
However, there are some total edge-cases when you really do want to run Isolator on a regular process, and that is possible.
Here's an article I wrote from a while back explaining how you can do this to a Windows Service, for example.
The basic algorithm holds:
Enable Typemock Isolator (either by setting up the profiling flags on the process or by running things through TMockRunner.exe).
Set up your expectations (this is where you mock DateTime.Now or whatever else you want mocked out).
Let the application finish starting up and run as normal.
The first step is easy enough - it's just like if you were running it in a unit test environment. It's the second step that can be difficult. It means you need to have some sort of "wrapper" or something that runs before the rest of your application is allowed to start that will set up your expectations. This normally happens in a test setup method or in the "arrange" part of your "arrange-act-assert" unit test. You'll see an example of this in my article.
Again, I'll warn you about performance. It's probably fine to do something like this in a test environment like you mention you're doing, but I don't think I'd do it in production.
A specific note about your program and the error you're seeing:
I tried to set up a reproduction of it and while I was able to mock other things, I wasn't able to get DateTime.Now mocking to work either. I got the same exception you're seeing.
For example, try this in your wrapper:
class Program
{
static void Main(string[] args)
{
ExpectationsSetup();
ConsoleApplication2.Program.Main(args);
}
public static void ExpectationsSetup()
{
// Mock something OTHER than DateTime.Now - this mocks
// the call to your wrapped application.
Isolate
.WhenCalled(() => ConsoleApplication2.Program.Main(null))
.DoInstead(ctx => Console.WriteLine("faked!"));
}
}
Running that wrapper through TMockRunner.exe, you'll actually get the mocking to work. However, switching it back to DateTime.Now, you'll get the exception again.
I did verify that mocking DateTime.Now in a unit test environment does work. So there must be something special about the unit test environment, though I don't know what.
Figuring out that difference is a little more in-depth than something that can be handled here. You should contact Typemock support with this one and explain the situation. They are pretty good about helping out. Be sure to send them a reproduction (e.g., a simple console app showing the issue) and you'll get a faster/better response.