Making actions get called in silverlight unit test with MOQ - silverlight

Lets say I have this
_articlesService.SaveAsync(Model, AddressOf OnSaveCompleted)
The OnSaveCompleteMethod do a couple of things, obviously. Its a
Protected Overridable Sub OnSaveCompleted(ByVal asyncValidationResult As AsyncValidationResult)
In my unittest. I need to run a mocked SaveAsync, and have OnSaveCompleted called in anyway, because the method sends out events that I need to know have been sent.
Right now, the code just walks past that method, thus its never executed.
Need help solving this because I'm stuck right now.

If I understand your context right:
you have a class under test which uses an ArticlesService
your ArticlesService (a collaborating class) is responsible for sending some events
you want to verify that your class under test is behaving correctly
you want to do that by checking for the events.
If that's the case, you may be making your class responsible for more than it needs to be. You only need to verify that the ArticlesService was asked to SaveAsync. You don't need to worry about what the ArticlesService then went off and did.
Think of it this way. You are a Class-Under-Test. You have too much work to do, so you've asked some other people to help you. You have two choices. You can either chase them up, worrying about whether they're doing it right, or you can just trust them.
Rather than micro-managing classes, you can write a separate test which gives some examples of the way the ArticlesService will work, which will check that the ArticlesService is doing its job correctly. Your CUT's responsibility is to delegate that work effectively.
If you actually need the events to be raised so that your CUT can respond, that's a separate aspect of its behaviour, and you can do it with Moq's "Raise" method, documented in "Events", here:
http://code.google.com/p/moq/wiki/QuickStart
Edit: You can also use "CallBack", documented on the same link, to do stuff with the args being passed to you, including OnSaveCompleted. Not sure if it's going to help or not; it's tricky to see what you're doing without both the code and the failing test. Good luck anyway!

Close, but not exactly like that.
We don't actually send out an event in the ArticleService.
The method SaveAsync takes an Article to be saved, and a method to be called once the saving is complete.
The problem is that the "OnSaveCompleted"-method isnt being called. (This method exists in the View Model Base class, so the service isnt sending the event, the viewmodel is.).
But we have our own implementation of WCF-service proxies so this is probably what's messing with us, since we dont use the generated code.
Think we will have to rework our infrastructure on the services abit to solve this.
So it's a special case, just wanted to throw the question out just in case. :)
Thanks anyway for the answer.

Related

APEX best practice

I am new to Salesforce apex coding. My first class that I am developing has 10 methods and is some 800 lines.
I haven’t added much of exception handling, so the size should swell further.
I am wondering, what the best practice for Apex code is... should I create 10 classes with 1 method instead of letting 1 class with 10 methods.
Any help on this would be greatly appreciated.
Thanks
Argee
What do you use for coding? Try to move away from Developer Console. VSCode has some decent plugins like Prettier or Apex PMD that should help you with formatting and making methods too complex. ~80 lines/method is so-so. I'd worry about passing long lists of parameters and having deeply nested code in functions rather than just their length.
There are general guidelines (from other languages, there's nothing special about Apex!) that ideally function should fit on 1 screen so programmer can see it whole without scrolling. Read this one, maybe it'll resonate with you: https://dzone.com/articles/rule-30-%E2%80%93-when-method-class-or
I wouldn't split it into separate files just for sake of it, unless you can clearly define some "separation of concerns". Say 1 trigger per object, 1 trigger handler class (ideally derived from base class). Chunkier bits not in the handler but maybe in some "service" style class that has public static methods and can operate whether called from trigger, visualforce, lightning web component, maybe some one-off data fix would need these, maybe in future you'd need to expose part of it as REST service. And separate file for unit tests (as blasphemous as it sounds - try to not write too many comments. As you're learning you'll need comments to remind yourself what built-in methods do but naming your functions right can help a lot. And a well-written unit test is better at demonstrating the idea behind the code, sample usage and expected errors than comments that can be often overlooked).
Exception handling is an art. Sometimes it's good to just let it throw an exception. If you have a method that creates Account, Contact and Opportunity and say Opportunity fails on validation rule - what should happen? Only you will know what's good. Exception will mean the whole thing gets rolled back (no "widow" Accounts) which sucks but it's probably "more stable" state for your application. If you naively try-catch it without Database.rollback() - how will you tell user to not create duplicates with 2nd click. So maybe you don't need too much error handling ;)

How to use single responsibility with functions

I've just read the book called clean code. The author Uncle Bob talks about a single responsibility that a function should have in a program. It should only do one thing.
Now, I would like to understand how is it now possible to reuse a code that does multiple things. Let's say I have a method called runTrafficAndCheckIfItPassed and it calls two methods inside of it: runTraffic and checkIfTrafficPassed.
Now let's say that in my software I need to run traffic and to check it's result in a lot of places in my software. sometimes i need to check that traffic has failed, and sometimes i need to check if it passed.
Why wouldn't it be right to call the runTrafficAndCheckIfItPassed function and why is it way better to call the functions inside separately?
As far as I see, if there will be a change in the runTraffic function, for example to receive another parameter, the change will be implemented in one place, only in runTrafficAndCheckIfItPassed, which we see will be kinda easy to maintain.
But if i will use the functions seperately i will need to change it in any place.
But Bob says it's wrong? Got any examples or tips why it is called wrong?

Angular $resource: update self from get

Is there any built-in method or conventionally correct approach to this? I'm not asking about issuing an update, but rather, requesting one. I could query for it again, but the goal is that the object reference stay the same.
The approach I've taken so far is to define an instance method called "refresh" that gets the same resource instance by ID and then iterates over its properties, copying them over to the original object (how I love thee _.extend). But it seems like something that might already be included functionality in ngResource and I just can't find it. If not, does Angular provide a means to make such a "refresh" method default to all $resources the same way save, delete, etc already are?
So I actually found the answer as I was writing the question, but I'm going to post it and answer anyway in case it might help someone else.
While writing that and looking stuff up, I realized that get is not restricted to being a static method of the resource. What threw me here was that on an instance, it's named $get. And lo, $get does exactly what I wanted. However it does not seem to be documented on Angular's site -- in fact the site says that only non-GET actions are instance methods, so who'd have thought? I mean, aside from that it seems totally obvious now.

Global property for DB access rather than passing DB around everywhere? Advice anyone?

Globals are evil right? At least everything I read says so, because something might alter the state of the global at any point.
However, I've a DB object that's a bit of a tramp in regards class parameters. The property below is an instance of a wrapper class that automatically works in MS Access or SQL - hence why it's not EF or some other ORM.
Public Property db As New DBI.DBI(DBI.DBI.modeenum.access, String.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0} ;Persist Security Info=True;Jet OLEDB:Database Password=""lkjhgfds8928""", GetRpcd("c:\cms")))
The code itself does have PostSharp for exception handling, so I'm thinking that I can conditionally handle oledb errors by logging them and re initialising the DB if it is Null.
Up till now, the solution has been to continually pass the db around as a parameter to every single class that needs it. Most of the data classes have a shared observablecollection that is built from structures that individually implement inotifyproperty changed. One of these is asynchronously built. The collection property checks if it's empty before firing off the private Async buildCollection sub.
Given that we don't use dependency injection (yet) as I need to learn it; is the Global property all that bad? Db is needed everywhere that data is pulled in or saved. The only places I don't need it at all is the View and its code behind.
It's not a customer facing project but it does need to be solid.
Any advice gratefully recieved!!
Passing the DB connection as a parameter into your classes IS using dependency injection, perhaps you just didn't recognize it as such. Hard coding the connection string in the callers is still code that is not free of dependencies, but at least your database accessors themselves are free of the dependency upon a global connection.
Globals aren't just evil because they change without notice - that's just one effect you see resulting from the bad design choice. They're evil because a design using them is brittle. Code that depends upon globals requires invisible stuff to be set correctly before calling it, and that leads to inter-dependencies between unrelated code. The invisible stuff becomes critically important stuff. Reading just the interface of a module that internally uses globals, how would I know that I have to call the SetupGlobalThing() method before calling it? What happens if I call IncrementGlobalThing() and DecrementGlobalThing() and MultiplyGlobalThing() in varying orders, depending on the function the user selects?
Instead, prefer stateless methods where you pass in all the stuff to be changed and used: IncrementThing(Integer thing) doesn't rely on hidden setup steps. It clearly does one thing: it increments the thing passed in.
It may help to think about it from a unit testing viewpoint. If you were to write a unit test to prove a specific module of code works, would you need to pass in a real database connection (hard*), or would you be able to pass in a fake database reference that meets your testing needs easily?
The best way to test your logic is to unit test it. The best way to test your class interfaces and method structure is to write unit tests that call them. If the class is hard to test, it's likely due to dependencies upon external things (globals, singletons, databases, inappropriate member variables, etc.)
The reason I called using a real database "hard" is that a unit test needs to be easy and fast to run. It shouldn't rely on slow or breakable or complex external things. Think about unit testing your software on the bus, with no network connection. Think about how much work it is to create a dummy database: you have to add users, you have to have the right version of schema in it, it has to be installed, it has to be filled with the right kind of testing data, you need network connectivity to it, all those things can make your testing unreliable. Instead, in a unit test you pass in a mock database, which simply returns values that exercise your code being tested.

Event Aggregation...What exactly is going on?

I have often times wondered about it but now that I have encountered a piece of logic that incorporates it, I thought I should go ahead and get some help on deciphering the fundamentals. The problem is as follows, I am looking at a WPF application that is utilizing the Composite Application Library. Within the source of the application I came across the following line of code in the Presentation of a view. For the sake of convinience I will call it Presentation A:
private void OnSomethingChanged(SomeArgumentType arguement)
{
UnityImplementation.EventAggregator.GetEvent<EventA>().Publish(null);
}
When I saw the method Publish in the above given method, my gut told me there must be a Subscribe somewhere and in another class, I will call it Presentation B there was the following:
UnityImplementation.EventAggregator.GetEvent(Of EventA).Subscribe(AddressOf OnSomeEventA)
There was a private function in the same class called OnSomeEventA that had some logic in it.
My question here is that how is everything wired over here? What exactly is achieved by the 'Publish' 'Subscribe' here? When 'something' changes, how does the compiler know it has to follow the logic in OnSomethingChanged that will 'Publish' an event that is 'Subscribed' by another class where the logic of the event handler has been described? It will be great to understand the underlying wiring of this process.
Thanks
The first time GetEvent<T> is called for each event (identified by the type parameter T) the EventAggregator creates an empty list of methods to call when that event is published. Typically, this will happen immediately before the first call to Publish or Subscribe (as in your examples).
Then:
Whenever Subscribe is called a method is added to the list.
Whenever Publish is called it walks through the list and makes those calls.
So, the call to Publish() in Presentation A results in all of the methods that have been registered by calling Subscribe being called, which in your example would include Presentation B's OnSomeEventA method.
Try setting a breakpoint in the OnSomeEventA method and take a look at the stack, and don't forget the source is available, too!

Resources