Cast Action to NSAction? - xamarin.ios

I was wondering if there's a cleaner work-around for this:
public class Sys
{
public static void DispatchAsync(Action action)
{
DispatchQueue.MainQueue.DispatchAsync(() => { action(); });
}
}
This Sys class is platform-neutral, so Action should be the method parameter type, but GCD's DispatchAsync won't take action if it's an Action type, only as an NSAction or the work-around here . . .

The class Sysisn't platform neutral if it is using Grand Central Dispatch. Better use Task.Run() and async/await.
And no, there is no better way than your workaround.

Related

ActiveWeb: mocking injected service

When mocking a service injected into a controller, a service method should return a mocked object, something like that:
public class EmptyInterventionServiceMock implements InterventionService {
#Override
public Intervention findByInvoiceNumber(String invoiceNumber, String language) {
return mockedIntervention(invoiceNumber, language);
}
protected Intervention mockedIntervention(String invoiceNumber, String language) {
return mock(Intervention.class);
}
}
Is it possible to mock some values to be return by the above mocked object (Intervention) to test fi they should be present in the generated JSON template ?
For example, depending on if Intervention has spare parts, services, states (all of them are just collections of other objects), etc. If so, JSON should contain the corresponding keys: services: [{....}], states: [{}], etc.
It would be nice to get the mocked object in the test and stub its return values. The only way I see to achieve that for the moment is to create a separate Mock service class and inject it in a test class as follows:
public class InterventionsControllerSpec extends ControllerSpec {
#Before
public void before() {
Injector injector = injector().bind(InterventionService.class).to(BaseInterventionServiceMock.class).create();
}
Where BaseInterventionServiceMock just extends EmptyInterventionServiceMock and stubs some methods return values by overriding its mockedIntervention method:
public class BaseInterventionServiceMock extends EmptyInterventionServiceMock {
#Override
protected Intervention mockedIntervention(String invoiceNumber, String language) {
Intervention intervention = mock(Intervention.class);
when(intervention.getString("ITV_DOCUMENT_NUMBER")).thenReturn("123");
when(intervention.getString("ITV_INVOICE")).thenReturn(invoiceNumber);
...
etc.
As it is far from ideal, I wonder if there is a DRYer way to do that ?
Thank you.
You are not missing anything. Your assumptions are correct. Creating a mock subclass of a service is how we do the testing. If you want a more elegant way, you can submit a proposal for consideration: https://github.com/javalite/activeweb/issues for consideration.

Mockito: Intercept any methods that return a type

I've an interface like this:
public interface ICustomer extends IEnd<Customer> {
String getId();
ICustomer id(String id);
ICustomer email(String email);
ICustomer description(String description);
}
I need to mock any methods which returns an ICustomer regardless of parameters.
When these methods are called, the self called ICustomer have to be returned.
Any ideas?
To do this you need a custom Answer class:
public class CustomerAnswer implements Answer {
#Override
public Object answer(InvocationOnMock invocation) throws Throwable {
Class retType = invocation.getMethod().getReturnType();
if (ICustomer.class.isInstance(retType)) {
return invocation.getMock();
}
// provide default logic here -- override with "when()" calls.
return null;
}
}
Then create your mock, specifying the default behavior:
Foo mockCustomer = mock(ICustomer.class, new CustomerAnswer());
Add, when() statements for other methods that need to be stubbed.
But as I commented in the OP, be sure you actually want to mock this class before you go thru all the trouble. Only mock when it will make the test code simpler. If you have some simple implementation of the interface that is just a POJO with fluent API (no side-effects, no complicated dependencies or injections), there is probably no need to mock it. Instead use a real instance, because the real instance already returns the original object.
If you need to verify() on the ICustomer object, then use a #Spy of a real instance of a ICustomer.

Groovy - can a method defined in an Interface have default values?

If the following is entered in Eclipse/STS (with groovy):
interface iFaceWithAnIssue {
def thisIsFine(a,b,c)
def thisHasProblems(alpha='va')
}
The only line that complains is the one trying to use a default value. I can not tell from the codehaus site if this is supported or not.
The IDE error is:
Groovy:Cannot specify default value for method parameter
So this makes me think it is not supported. As there will be multiple implementations, I wanted to use an interface here. I don't really need the default value in the interface, but there is an error trying to fulfill the interface contract if the implementation class then tries to default this argument. Is there any way?
No, you cannot.
When you define a default value, Groovy actually creates multiple methods in your class, so for example:
class Test {
void something( a=false ) {
println a
}
}
Actually creates
public void something(java.lang.Object a) {
this.println(a)
}
and
public void something() {
this.something(((false) as java.lang.Object))
}
This can't be done as it stands in Interfaces.
You could do:
interface iFaceWithAnIssue {
def thisHasProblems()
def thisHasProblems(alpha)
}
Then
class Test implements iFaceWithAnIssue {
// This covers both Inteface methods
def thisHasProblems(alpha='va') {
// do something
}
}

EF generic method overloading

I'd like make possible a generic method overload.
Since I need to create an ObjectSet<..> without knowing the generic type contained in, I wold build something like this:
public IQueryable<T> MyMethod<T>() where T : class, (IMyFirst || IMySecond) //notice the syntax..!
{
if(typeOf(T) is IMyFirst..
else ...
}
How can I reach my purpose..?
Update:
#BrokenGlass wrote:
This type of constraint is not possible in C# - you could however constrain to IFoo and have IMyFirst and IMySecond both implement IFoo.
But that suggestion is not applicable, please see this:
interface1 { property1 {..}}
interface2 { property2 {..}}
interfaceIFoo : interface1, interface2 { }
by any method:
MyWrapper.Retrieve<EntityProduct>(myObjContext); //error-> EntityProduct implements interface1 only!!
by other any method:
MyWrapper.Retrieve<EntityOrder>(myObjContext); //error-> EntityOrder implements interface2 only!!
and here:
public static IQueryable<T> Retrieve<T>(ObjectContext context) where T :class, interfaceIFoo
{
var query = context.CreateObjectSet<T>().AsQueryable();
//...
This type of constraint is not possible in C# - you could however constrain to IFoo and have IMyFirst and IMySecond both implement IFoo.
If you can live with dependencies on Entity Framework you could alternatively also use EntityObject
A disjunctive generic constraint doesn't really make sense. Those constraints provide compile-time information to the method, so there's not much point in constraints that result in an ambiguous type at compile time. For instance, if your method is just going to resort to run-time type checking, you might as well just do this:
public IQueryable<T> MyMethod<T>() where T : class
{
if (typeOf(T) is IMyFirst) ...
else ...
}
If you feel you need the type checking on input and a pseudo-abstraction, perhaps extension methods that happen to be identically named would suffice:
public static IQueryable<IMyFirst> MyMethod(this IMyFirst input)
{
return ...
}
public static IQueryable<IMySecond> MyMethod(this IMySecond input)
{
return ...
}

ViewHelper newable/injectable dilemma

I'm trying to design an application following Misko Heverys insights. It's an interesting experiment and a challenge. Currently I'm struggling with my ViewHelper implementation.
The ViewHelper decouples the model from the view. In my implementation it wraps the model and provides the API for the view to use. I'm using PHP, but I hope the implementation is readable for everyone:
class PostViewHelper {
private $postModel;
public function __construct(PostModel $postModel) {
$this->postModel = $postModel;
}
public function title() {
return $this->postModel->getTitle();
}
}
In my template (view) file this could be called like this:
<h1><?php echo $this->post->title(); ?></h1>
So far so good. The problem I have is when I want to attach a filter to the ViewHelpers. I want to have plugins that filter the output of the title() call. The method would become like this:
public function title() {
return $this->filter($this->postModel->getTitle());
}
I need to get observers in there, or an EventHandler, or whatever service (in what I see as a newable, so it needs to be passed in through the stack). How can I do this following the principles of Misko Hevery? I know how I can do this without it. I'm interested in how for I can take it and currently I don't see a solution. ViewHelper could be an injectable too, but then getting the model in there is the problem.
I didn't find the blog post you referenced very interesting or insightful.
What you are describing seems more like a Decorator than anything to do with dependency injection. Dependency injection is how you construct your object graphs, not their state once constructed.
That said, I'd suggest taking your Decorator pattern and running with it.
interface PostInterface
{
public function title();
}
class PostModel implements PostInterface
{
public function title()
{
return $this->title;
}
}
class PostViewHelper implements PostInterface
{
public function __construct(PostInterface $post)
{
$this->post = $post;
}
public function title()
{
return $this->post->title();
}
}
class PostFilter implements PostInterface
{
public function __construct(PostInterface $post)
{
$this->post = $post;
}
public function title()
{
return $this->filter($this->post->title());
}
protected function filter($str)
{
return "FILTERED:$str";
}
}
You'd simply use whatever DI framework you have to build this object graph like so:
$post = new PostFilter(new PostViewHelper($model)));
I often use this approach when building complex nested objects.
One problem you might run into is defining "too many" functions in your PostInterface. It can be a pain to have to implement these in every decorator class. I take advantage of the PHP magic functions to get around this.
interface PostInterface
{
/**
* Minimal interface. This is the accessor
* for the unique ID of this Post.
*/
public function getId();
}
class SomeDecoratedPost implements PostInterface
{
public function __construct(PostInterface $post)
{
$this->_post = $post;
}
public function getId()
{
return $this->_post->getId();
}
/**
* The following magic functions proxy all
* calls back to the decorated Post
*/
public function __call($name, $arguments)
{
return call_user_func_array(array($this->_post, $name), $arguments);
}
public function __get($name)
{
return $this->_post->get($name);
}
public function __set($name, $value)
{
$this->_post->__set($name, $value);
}
public function __isset($name)
{
return $this->_post->__isset($name);
}
public function __unset($name)
{
$this->_post->__unset($name);
}
}
With this type of decorator in use, I can selectively override whatever method I need to provide the decorated functionality. Anything I don't override is passed back to the underlying object. Multiple decorations can occur all while maintaining the interface of the underlying object.

Resources