AxonFramework: How to test #EventHandler - testing

I have this component which integrates with other services through a RabbitMQ queue:
#Component
#ProcessingGroup("amqpProcessor")
public class ExternalEventsHandler {
#EventHandler
public void on(SomeOtherServiceEvent event) {
// Dispatches some command
}
}
How should I test this?
#Test
public void shouldReactToSomeOtherServiceEvent() {
//TODO
}

The best way is just to instantiate or inject your event handler class in the unit test, instantiate a test event, and simply call the method. Something like this:
#Mock
private FooRepository fooRepository;
private FooEventHandler fooEventHandler;
#Before
public void before() {
fooEventHandler = new FooEventHandler(fooRepository);
}
#Test
public void createFoo() {
fooEventHandler.createFoo(new FooCreatedEvent("fooId");
ArgumentCaptor<Foo> argument = ArgumentCaptor.forClass(Foo.class);
verify(fooRepository, times(1)).save(argument.capture());
assertTrue(argument.getValue().getId(), "fooId"));
}

Related

JUnit5 afterAll callback fires at the end of each test class and not after all tests

I have 15 JUnit5 classes with tests. When I run them all from maven, the afterAll() is executed 15 times which causes 15 notifications to a Slack Webhook. Is there anything else I need to only send one notification?
public class TestResultsExtensionForJUnit5 implements TestWatcher, AfterAllCallback {
#Override
public void afterAll(ExtensionContext extensionContext) throws Exception {
sendResultToWebHook();
}
#Override
public void testDisabled(ExtensionContext context, Optional<String> reason) {
totalTestDisabled = totalTestDisabled + 1;
}
#Override
public void testSuccessful(ExtensionContext context) {
totalTestPassed = totalTestPassed + 1;
}
#Override
public void testAborted(ExtensionContext context, Throwable cause) {
totalTestAborted = totalTestAborted + 1;
}
#Override
public void testFailed(ExtensionContext context, Throwable cause) {
totalTestFailed = totalTestFailed + 1;
}
}
#ExtendWith(TestResultsExtensionForJUnit5.class)
public class Random1Test {}
The best way is to implement and install a TestExecutionListener from the JUnit Platform, as it is described in the User Guide at https://junit.org/junit5/docs/current/user-guide/#launcher-api-listeners-custom -- override the default testPlanExecutionFinished​(TestPlan testPlan) method with your notifying call. Here, all tests from all engines are finished.

Where do Before and After hooks go in Cucumber

I have a fairly simple Cucumber test framework with a feature file, a step definitions file, and a test runner class that looks like this:
#RunWith(Cucumber.class)
#CucumberOptions(features = "src/test/java/com/tests/cucumber/features/ui/ExampleTest.feature",
glue = { "com.tests.cucumber.stepdefinitions" },
)
public class ExampleTestRunner {
}
This runs a scenario in the feature file just fine. Now I want to add a Before and After hook to do some setup and teardown, but I can't for the like of me get the hooks to run. I've tried adding the hooks to the ExampleTestRunner and to the StepDefinition class, but they never run. Where should I put these hooks? At the moment, the hooks just look like this, but I'll add content to them once I've worked this out!
package com.tests.cucumber.stepdefinitions;
import cucumber.api.java.After;
import cucumber.api.java.Before;
public class StepDefinitions {
#Before
public void before() {
System.out.println("starting before()");
}
}
Thanks for any help.
I am a little hesitant to answer this question even though I managed to get this to work. As far as I can tell, the problem was that I had added the Before and After methods in classes that were extended by other classes. In this situation, the tests would not run. I had to add the Before and After methods to a class that was not extended.
It feels like this is similar to the situation in which if you specify a step definition in a class that is extended by another class, then the step definition is considered to have a duplicate definition. Do I have the correct diagnosis here?
I use like this;
Runner Class:
#RunWith(Cucumber.class)
#CucumberOptions(
features = {"src\\test\\features\\ui_features"},
glue = {"com\\base\\tm\\auto_reg\\tests\\ui_tests\\price_features"},
plugin = {"com.cucumber.listener.ExtentCucumberFormatter:"}
)
public class PriceFeatureRunner {
#BeforeClass
public static void setup() {
RunnerUtil.setup(PriceFeatureRunner.class);
}
#AfterClass
public static void teardown() {
RunnerUtil.teardown();
}
}
RunnerUtil.java:
public class RunnerUtil {
public static void setup(Class<?> clazz) {
String reportPath = "target/cucumber-reports/" + clazz.getSimpleName().split("_")[0] + "_report.html";
ExtentProperties extentProperties = ExtentProperties.INSTANCE;
extentProperties.setReportPath(reportPath);
}
public static void teardown() {
UiHooks uiHooks = new UiHooks();
uiHooks.afterScenario();
ExtentReportConfiguration.configureExtentReportTeardown();
}
}
UiHooks.java
public class UiHooks implements HookHelper {
public static final String BASE_URL = "https://www.stackoverfow.com/";
private Scenario scenario;
#Override
#Before
public void beforeScenario(Scenario scenario) {
this.scenario = scenario;
Reporter.assignAuthor(System.getProperty("user.name"));
}
#Override
#After
public void afterScenario() {
if (HookUtil.driver != null) {
HookUtil.driver.quit();
}
if (HookUtil.seleniumBase != null) {
HookUtil.seleniumBase.stopService();
}
}
#Override
#After
public void afterTest() {
if (HookUtil.driver != null) {
HookUtil.driver.quit();
}
if (HookUtil.seleniumBase != null) {
HookUtil.seleniumBase.stopService();
}
}
}
HookHelper.Java
public interface HookHelper {
#Before
void beforeScenario(Scenario scenario);
#After
void afterScenario();
void afterTest();
}

How to test a constructor call in JMockit for the following piece of code

public class HuronClassloader extends URLClassLoader {
public HuronClassloader(Logger logger) {
super(new URL[0]);
this.logger = logger;
}
public void doLogic() throws ClasspathFormattingException {
// logic go heer
}
// How to test the doLogic method using JMockit?
You can try as follows; #Injectable will automatically inject the mock Logger object to the constructor when initializing your tested class.
import mockit.Injectable;
import mockit.Tested;
...
#Tested
HuronClassloader loader;
#Injectable
Logger logger;
#Test
public void testSomeMethod() {
//Optionally you can set expectation on your mock
new Expectations() {{
logger.someMethod(); result = ...;
}};
loader.doLogic();
}

JUnit: Is there a RunListener method, which is called after #After annotated method?

Is there a way to invoke a method after all #After annotated methods of a test method had been run?
I need this for a special framework for my company.
In testng i can use the afterInvocation method, which is called after every configuration method. Is there some alternative in JUnit?
A rule will run after all the #Afters. The ExternalResource could be abused in order to do what you want:
public class VerifyTest {
#Rule public ExternalResource externalResource = new ExternalResource() {
public void after() {
System.out.println("ExternalResource.after");
}
};
#After
public void after1() {
System.out.println("after1");
}
#After
public void after2() {
System.out.println("after2");
}
#Test
public void testVerify throws IOException {
}
}

How can I inject multiple repositories in a NServicebus message handler?

I use the following:
public interface IRepository<T>
{
void Add(T entity);
}
public class Repository<T>
{
private readonly ISession session;
public Repository(ISession session)
{
this.session = session;
}
public void Add(T entity)
{
session.Save(entity);
}
}
public class SomeHandler : IHandleMessages<SomeMessage>
{
private readonly IRepository<EntityA> aRepository;
private readonly IRepository<EntityB> bRepository;
public SomeHandler(IRepository<EntityA> aRepository, IRepository<EntityB> bRepository)
{
this.aRepository = aRepository;
this.bRepository = bRepository;
}
public void Handle(SomeMessage message)
{
aRepository.Add(new A(message.Property);
bRepository.Add(new B(message.Property);
}
}
public class MessageEndPoint : IConfigureThisEndpoint, AsA_Server, IWantCustomInitialization
{
public void Init()
{
ObjectFactory.Configure(config =>
{
config.For<ISession>()
.CacheBy(InstanceScope.ThreadLocal)
.TheDefault.Is.ConstructedBy(ctx => ctx.GetInstance<ISessionFactory>().OpenSession());
config.ForRequestedType(typeof(IRepository<>))
.TheDefaultIsConcreteType(typeof(Repository<>));
}
}
My problem with the threadlocal storage is, is that the same session is used during the whole application thread. I discovered this when I saw the first level cache wasn't cleared. What I want is using a new session instance, before each call to IHandleMessages<>.Handle.
How can I do this with structuremap? Do I have to create a message module?
You're right in that the same session is used for all requests to the same thread. This is because NSB doesn't create new threads for each request. The workaround is to add a custom cache mode and have it cleared when message handling is complete.
1.Extend the thread storage lifecycle and hook it up a a message module
public class NServiceBusThreadLocalStorageLifestyle : ThreadLocalStorageLifecycle, IMessageModule
{
public void HandleBeginMessage(){}
public void HandleEndMessage()
{
EjectAll();
}
public void HandleError(){}
}
2.Configure your structuremap as follows:
For<<ISession>>
.LifecycleIs(new NServiceBusThreadLocalStorageLifestyle())
...
Hope this helps!