How to create actor with parameterized constructor from testprobe - akka.net

I am trying test to MyActor for sending a MessageB to itself on condition. MyActor takes setting as constructor parameter. Setting doesn't have setter cause it is intended to be immutable after creation.
public class MyActor : ReceiveActor
{
private bool Setting { get; }
public MyActor(bool setting)
{
Setting = setting;
Receive<MessageA>(message => HandleMessageA(message));
}
public void HandleMessageA(MessageA message)
{
if (Setting)
Self.Tell(new MessageB);
}
}
And here is the test
[Test]
public void HandleMessageA_SettingIsTrue_MessageBIsSent()
{
bool setting = true;
var testProbe = this.CreateTestProbe();
var myActor = Props.Create<MyActor>(testProbbe);
myActor.Tell(new MessageA);
myActor.ExpectMsg<MessageB>();
}
My problem is that i don't know how to pass bool setting to constructor.
Well I can write it like this
bool setting = true;
var myActor = Props.Create<MyActor>(setting);
And this way myActor will have settings set. But than I didn't use TestProbe and therefore will not be able to listen for expected message. So my question is how make Arrange section of test correctly?

A great guide to testing with Akka.NET describes how to create actors within the test system:
Create your actors within Sys so that your actors exist in the same
ActorSystem as the TestActor.
// create an actor in the TestActorSystem
var actor = Sys.ActorOf(Props.Create(() => new MyActorClass()));

Well the situation you have created is rather artificial. Because in a real world scenario you would either send MessageB to another actor. Which you would then be able to substitute with a TestProbe. Or you would verify the sideeffect that your messageB would have. So for example sending messageB to Self, would update some property on your actor, which you could then Test for.
Also see Chima's response, he shows the correct way to create your actor. Because only instantiating the Props is not enough.
And some general advice. When testing actors, you will want to try to refrain from testing for individual messages. Try and test the outcome (or side-effect) of sending those messages instead. That way your tests are a lot less brittle should you ever refactor your Actor's interactions

Related

Kotlin - Here Maps - Get address out of callback function

I am attempting to get the address out of the callback function. I have been reading the documentation for CallBacks and some posts but still don't get why this is not working, as at the moment of returning the 'address' variable the callback has already finished.
private fun getAddressForCoordinates(geoCoordinates: GeoCoordinates):String {
address = "unchanged"
val maxItems = 1
val reverseGeocodingOptions = SearchOptions(LanguageCode.EN_GB, maxItems)
searchEngine.search(geoCoordinates, reverseGeocodingOptions, addressSearchCallback)
return address
}
private val addressSearchCallback =
SearchCallback { searchError, list ->
if (searchError != null) {
//showDialog("Reverse geocoding", "Error: $searchError")
Toast.makeText(context, "Error: $searchError", Toast.LENGTH_LONG).show()
return#SearchCallback
}
Toast.makeText(
context,
"Reverse geocoded address:" + list!![0].address.addressText,
Toast.LENGTH_LONG
).show()
address = list[0].address.addressText
}
From your code and comment I assume you are not familiar with the concept of asynchronous execution. That concept was well described here. I'll quote the main point:
When you execute something synchronously, you wait for it to finish
before moving on to another task. When you execute something
asynchronously, you can move on to another task before it finishes.
The fact that search() requires providing a callback and it doesn't simply return search results, is a good indication that it is most probably asynchronous. Invoking it is like saying: "Search for the data in the background and let me know when you have it. This is my email address - please send me my results there". Where email address is your callback. Invoking search() method does not block execution of your code, it does not wait for results - it only schedules searching and returns almost immediately.
Asynchronous processing is usually more tricky than a regular, synchronous code, but in many cases it is more efficient. In your case you can either try to "convert" original async API of the library to sync API that your code expects - but this is not recommended approach. Or you can redesign your code, so it will work asynchronously. For example, instead of doing this:
fun yourMethodThatNeedsAddress() {
val address = getAddressForCoordinates()
doSomethingWithAddress(address)
}
You need to do this:
fun yourMethodThatNeedsAddress() {
scheduleGetAddressForCoordinates() // renamed getAddressForCoordinates()
}
fun addressSearchCallback() {
...
doSomethingWithAddress(address)
}
So, whatever you planned to do with the acquired address, you can't do this straight after you started searching. You need to wait for a callback and then continue with processing of your address from there.
The SearchEngine from the 4.x HERE SDK needs an online connection as it is fetching results from a remote backend. This may take a few milliseconds, depending on your network connection. So, whenever you perform a search request, you need to wait until the callback is called:
searchEngine.search(geoCoordinates, reverseGeocodingOptions, addressSearchCallback)
When you call this, you pass addressSearchCallback as parameter. The implementation for addressSearchCallback can look like in your example. It will be called whenever the operation has finished. If the device is offline, then an error will be shown.
Note that the search() method is not returning any results immediately. These are passed to the callback, which happens asynchronously on a background thread. Thus, your application can continue to work without blocking any UI.
Once results are retrieved, the callback will be executed by the HERE SDK on the main thread.
So, if your code needs to do something with the address result, you have to do it inside the onSearchCompleted() method defined by the SearchCallback. If you write it in plain Java without lambda notation, it is more visible: You create a new SearchCallback object and pass it as parameter to the SearchEngine. The SearchEngine stores the object and executes the object's onSearchCompleted() whenever it thinks it's the right time:
private SearchCallback addressSearchCallback = new SearchCallback() {
#Override
public void onSearchCompleted(#Nullable SearchError searchError, #Nullable List<Place> list) {
if (searchError != null) {
showDialog("Reverse geocoding", "Error: " + searchError.toString());
return;
}
// If error is null, list is guaranteed to be not empty.
showDialog("Reverse geocoded address:", list.get(0).getAddress().addressText);
// Here is the place to do something more useful with the Address object ...!
}
};
I took this from this GitHub code snippet. Note that there is also an OfflineSearchEngine, that works without an internet connection, but for some reason it follows the same pattern and executes the task asynchronously.
private void getAddressForCoordinates(GeoCoordinates geoCoordinates) {
int maxItems = 1;
SearchOptions reverseGeocodingOptions = new SearchOptions(LanguageCode.EN_GB, maxItems);
searchEngine.search(geoCoordinates, reverseGeocodingOptions, new SearchCallback() {
#Override
public void onSearchCompleted(#Nullable SearchError searchError, #Nullable List<Place> list) {
if (searchError != null) {
showDialog("Reverse geocoding", "Error: " + searchError.toString());
return;
}
// If error is null, list is guaranteed to be not empty.
showDialog("Reverse geocoded address:", list.get(0).getAddress().addressText);
}
});
}
SearchEngine, a SearchOptions instance needs to be provided to set the desired LanguageCode. It determines the language of the resulting address. Then we can make a call to the engine's search()-method to search online for the address of the passed coordinates. In case of errors, such as when the device is offline, SearchError holds the error cause.
The reverse geocoding response contains either an error or a result: SearchError and the result list can never be null at the same time - or non-null at the same time.
The Address object contained inside each Place instance is a data class that contains multiple String fields describing the address of the raw location, such as country, city, street name, and many more. Consult the API Reference for more details. If you are only interested in receiving a readable address representation, you can access addressText, as shown in the above example. This is a String containing the most relevant address details, including the place's title.
Please refer to following link for detailed documentation on search() function and parameters associated with it.
https://developer.here.com/documentation/android-sdk-explore/4.4.0.2/dev_guide/topics/search.html

Akka.Net switching behavior with Become()

I have built as simple actor which accepts two messages: TicketValidated and BarrierPush but the switching is not happening as intended.
public class TurnstileActor : ReceiveActor
{
public TurnstileActor()
{
Become(Locked);
}
public void Locked()
{
Receive<TicketValidated>(msg => Become(Unlocked));
Receive<BarrierPush>(msg => { Console.WriteLine("Locked");});
}
public void Unlocked()
{
Receive<TicketValidated>(msg =>
Console.WriteLine("Unlocked"));
Receive<BarrierPush>(msg => Become(Locked));
}
}
Main class
var system = ActorSystem.Create("ActorSystem");
var actor = system.ActorOf<TurnstileActor>("actor");
actor.Tell(new TicketValidated());
Actual execution is: the Locked() method is called from the constructor and TicketValidated message is received. Become(Unlocked) is executed correctly and it enters Unlocked() method but then Console.WriteLine("Unlocked") is not called.
Could the Akka.Net library be broken?
To understand this behaviour, consider what happens when Become(Unlocked) is executed, and it enters the Unlocked() method. The Unlocked method in turn invokes the Receive method twice: These 2 calls to Receive register the new behaviour of this actor, affecting subsequent messages sent to this actor instance. The lambdas passed in to the Receive methods are not executed at this time - they represent the new behaviour that is registered, and that will be seen when subsequent messages are received.
That explains why "Unlocked" is not written to the console when "Become(Unlocked)" is executed - It will only be seen if the next message received is another "TicketValidated".

How do i wireup NServiceBus' SqlSaga in a test scenario?

https://docs.particular.net/nservicebus/testing/ has a very neat example of how to test a simple Saga. Unfortunately it does not explain, how to do the same with a SqlSaga - ie. a Saga with persistence of state to a database.
Given this saga:
public class SomeFancySaga : SqlSaga<MySagaData>,
IAmStartedByMessages<ImportantCommand>
{
protected override string CorrelationPropertyName => nameof(Data.MyPrimaryKey);
protected override void ConfigureMapping(IMessagePropertyMapper mapper)
{
mapper.ConfigureMapping<ImportantCommand>(x => x.CommandId);
}
public async Task Handle(ImportantCommand command, IMessageHandlerContext context)
{
if (Data.State == MyState.ReadyForUse)
<do some stuff>
}
...
}
If I try to write test-code like the example in the link, I would do something like this:
// arrange
var context = new NServiceBus.Testing.TestableMessageHandlerContext();
var command = ImportantCommand.Create();
var sut = new CreateSomeFancySaga();
// act
sut.Handle(command, context);
// assert
...
The call to sut.Handle() will throw a NullReferenceException, because the Saga property Data has not been initialized.
How do I correctly wireup the saga for testing so that:
Data is initialized
A real database connection is not really needed
We have a related code sample showing unit testing in more detail: https://docs.particular.net/samples/unit-testing/. That includes a couple of tests for saga (SagaTests.cs).
You can take this as a starting point and modify the saga tests in the following way:
Add NServiceBus.Persistence.Sql package.
Modify the DiscountPolicy policy saga to inherit from SqlSaga instead of a Saga.
Resolve compilation errors (add missing method and property, you can keep them empty, plus remove the ConfigureHowToFindSaga method).
I hope that helps, but let me know if there's anything missing or your scenario can't be tested this way.

Actionscript, can a class be accessed using a variable name?

I wish to access many classes and variables, I would like to do this by dynamically setting the class name and variable name. Currently I am using
MyClass["myVariable1"]
to dynamically access the variable name
MyClass.myVariable1
I want to also dynanmically acces the class name, something like
["MyClass"]["myVariable1"]
But this does not work.
The purpose is that I have shared object with many user settings, I want to iterate through the shared object and set all the user settings across all the classes. I think if I cant dynamically access the class I must have a statement for each and every class name/variable.
I advise against such a practice. Although technically possible, it is like welcoming a disaster into the app architecture:
You rely on something you have no apparent control of: on the way Flash names the classes.
You walk out of future possibility to protect your code with identifier renaming obfuscation because it will render your code invalid.
Compile time error checks is better than runtime, and you are leaving it to runtime. If it happens to fail in non-debug environment, you will never know.
The next developer to work with your code (might be you in a couple of years) will have hard time finding where the initial data coming from.
So, having all of above, I encourage you to switch to another model:
package
{
import flash.net.SharedObject;
public class SharedData
{
static private var SO:SharedObject;
static public function init():void
{
SO = SharedObject.getLocal("my_precious_shared_data", "/");
}
static public function read(key:String):*
{
// if (!SO) init();
return SO.data[key];
}
static public function write(key:String, value:*):void
{
// if (!SO) init();
SO.data[key] = value;
SO.flush();
}
// Returns stored data if any, or default value otherwise.
// A good practice of default application values that might
// change upon user activity, e.g. sound volume or level progress.
static public function readSafe(key:String, defaultValue:*):*
{
// if (!SO) init();
return SO.data.hasOwnProperty(key)? read(key): defaultValue;
}
}
}
In the main class you call
SharedData.init();
// So now your shared data are available.
// If you are not sure you can call it before other classes will read
// the shared data, just uncomment // if (!SO) init(); lines in SharedData methods.
Then each class that feeds on these data should have an initialization block:
// It's a good idea to keep keys as constants
// so you won't occasionally mistype them.
// Compile time > runtime again.
static private const SOMAXMANA:String = "maxmana";
static private const SOMAXHP:String = "maxhp";
private var firstTime:Boolean = true;
private var maxmana:int;
private var maxhp:int;
// ...
if (firstTime)
{
// Make sure it does not read them second time.
firstTime = false;
maxhp = SharedData.readSafe(SOMAXHP, 100);
maxmana = SharedData.readSafe(SOMAXMANA, 50);
}
Well, again. The code above:
does not employ weird practices and easy to understand
in each class anyone can clearly see where the data come from
will be checked for errors at compile time
can be obfuscated and protected
You can try getting the class into a variable and going from there:
var myClass:Class = getDefinitionByName("MyClass") as Class;
myClass["myVariable1"] = x;

Using Rhino Mocks, why does invoking a mocked on a property during test initialization return Expected call #1, Actual call #0?

I currently have a test which tests the presenter I have in the MVP model. On my presenter I have a property which will call into my View, which in my test is mocked out. In the Initialization of my test, after I set my View on the Presenter to be the mocked View, I set my property on the Presenter which will call this method.
In my test I do not have an Expect.Call for the method I invoke, yet when I run I get this Rhino mock exception:
Rhino.Mocks.Exceptions.ExpectationViolationException: IView.MethodToInvoke(); Expected #1, Actual #0..
From what I understand with Rhino mocks, as long as I am invoking on the Mock outside the expecting block it should not be recording this. I would imagine the test to pass. Is there a reason it is not passing?
Below is some code to show my setup.
public class Presenter
{
public IView View;
public Presenter(IView view)
{
View = view
}
private int _property;
public int Property
get { return _property;}
set
{
_property = value;
View.MethodToInvoke();
}
}
... Test Code Below ...
[TestInitialize]
public void Initilize()
{
_mocks = new MockRepository();
_view = _mocks.StrictMock<IView>();
_presenter = new Presenter(_view);
_presenter.Property = 1;
}
[TestMethod]
public void Test()
{
Rhino.Mocks.With.Mocks(_mocks).Expecting(delegate
{
}).Verify(delegate
{
_presenter.SomeOtherMethod();
});
}
Why in the world would you want to test the same thing each time a test is run?
If you want to test that a specific thing happens, you should check that in a single test.
The pattern you are using now implies that you need to
- set up prerequisites for testing
- do behavior
- check that behavior is correct
and then repeat that several times in one test
You need to start testing one thing for each test, and that help make the tests clearer, and make it easier to use the AAA syntax.
There's several things to discuss here, but it certainly would be clearer if you did it something like:
[TestMethod]
ShouldCallInvokedMethodWhenSettingProperty()
{
var viewMock = MockRepository.GenerateMock<IView>()
var presenter = new Presenter(viewMock);
presenter.Property = 1;
viewMock.AssertWasCalled(view => view.InvokedMethod());
}
Read up more on Rhino Mocks 3.5 syntax here: http://ayende.com/Wiki/Rhino+Mocks+3.5.ashx
What exactly are you trying to test in the Test method?
You should try to avoid using strict mocks.
I suggest using the Rhino's AAA syntax (Arrange, Act, Assert).
The problem lied with me not understanding the record/verify that is going on with Strict mocks. In order to fix the issue I was having this is how I changed my TestInitilize function. This basicaly does a quick test on my intial state I'm setting up for all my tests.
[TestInitialize]
public void Initilize()
{
_mocks = new MockRepository();
_view = _mocks.StrictMock<IView>();
_presenter = new Presenter(_view);
Expect.Call(delegate { _presenter.View.InvokedMethod(); });
_mocks.ReplayAll();
_mocks.VerifyAll();
_mocks.BackToRecordAll();
_presenter.Property = 1;
}