Microsoft Fakes - Stubbing an Extension Method Shouldn't Work But It Does - moq

I have an interface, ILoader, on which I have defined an extension method CheckLoaderDatabaseConnection:
//the extension method
public static class LoaderExtensions
{
public static void CheckLoaderDatabaseConnection(this ILoader loader)
{
//data access stuff
}
All the doumentation out there tells me I have to use shims when I want to stub an extension method because the method is static and it can't be stubbed.
True, it doesn't work in Moq because I've tried it.
But I can stub the interface in Fakes:
var loader = new MyNamespace.Fakes.StubILoader() { };
In my unit test, I pass in the stub to the constructor of the concrete instance I'm testing and when it gets to this line:
loader.CheckLoaderDatabaseConnection();
It calls the stubbed method (which does nothing) and works ok.
Why is this? I must be missing something. I haven't had to use shims here at all (though I can't stub it in Moq - when I try that, the real world extension is called & the whole thing blows up)

No, the extension method wasn't getting invoked but after rebooting from a blue screen of death earlier the extension method is now getting invoked and the unit test is failing as I would expect.
Don't understand how this was working for several days though; something weird & I don't think this question can be answered.

Related

return model instance from controller to test class in laravel

i am unit testing in laravel with Phpunit. The situation is i have to return a model instance from the controller back to the testing class. There i will use the attributes of that object to test an assertion. How can i achieve that?
Currently i am json encoding that instance into the response. And using it in a way that works but is ugly. Need a clearer way.
This is my test class:
/** #test
*/
function authenticated_user_can_create_thread()
{
//Given an authenticated user
$this->actingAs(factory('App\User')->create());
//and a thread
$thread = factory('App\Thread')->make();
//when user submits a form to create a thread
$created_thread = $this->post(route('thread.create'),$thread->toArray());
//the thread can be seen
$this->get(route('threads.show',['channel'=>$created_thread->original->channel->slug,'thread'=>$created_thread->original->id]))
->assertSee($thread->body);
}
and this is the controller method:
public function store(Request $request)
{
$thread = Thread::create([
'user_id'=>auth()->id(),
'title'=>$request->title,
'body'=>$request->body,
'channel_id'=>$request->channel_id,
]);
if(app()->environment() === 'testing')
{
return response()->json($thread); //if request is coming from phpunit/test environment then send back the creted thread object as part of json response
}
else
return redirect()->route('threads.show',['channel'=>$thread->channel->slug,'thread'=>$thread->id]);
}
As you can see in the test class, i am receiving the object returned from controller in the $created_thread variable. However, controller is returning an instance of Illuminate\Foundation\Testing\TestResponse, so the THREAD that is embedded in this response is not easy to extract. You can see i am doing
--> $created_thread->original->channel->slug,'thread'=>$created_thread->original->id]. But i am sure there is a better way of achieving the same thing.
Can anyone please guide me to the right direction?
PHPUnit is a unit testing suite, hence the name. Unit testing is, by
definition, writing tests for each unit -- that is, each class, each
method -- as separately as possible from every other part of the
system. Each thing users could use, you want to try to test that it --
and only it, apart from everything else -- functions as specified.
Your problem is, there is nothing to test. You haven't created any method with logic which could be tested. Testing controllers action is pointless, as it only proves that controllers are working, which is a Laravel creators thing to check.

Autofac SingleInstance() and Xamarin Forms

To start, let me say that I have read several questions here about SingleInstance, but still cannot find a direct answer that helps me. That said, I apologize if I missed anything.
Here's my question:
I am building a Xamarin Forms app for iOS and Android. I have a single AppInitializer class in a PCL where I register all of my interface dependencies using Autofac. I then assign the Container from the builder as a static property on the app class. The problem I encounter is that while I'm registering everything with .SingleInstance(), I'm not actually getting a single instance.
Init Logic Example:
var builder = new ContainerBuilder();
builder.RegisterType<ErrorHandler>().SingleInstance().As<IErrorHandler>();
…
builder.RegisterType<MemberViewModel>().SingleInstance().As<IMemberViewModel>();
…
AppContainer.Current = builder.Build();
I am letting Autofac handle resolving interfaces in my constructors. For example:
public MemberViewModel(ISettingsViewModel settings, IErrorHandler errorHandler, …) : base(settings, errorHandler){…}
I then use said model on a page as below:
Example page usage:
public ProfilePage()
{
InitializeComponent();
var displayModel = Model.CurrentMember;
…
}
…
**public IMemberViewModel Model =>
AppContainer.Current.Resolve<IMemberViewModel>();**
In this example I set Model.CurrentMember's properties immediately before arriving on this page. I've set breakpoints and know for a fact this is happening. However, when I resolve the instance of the model, the properties on CurrentMember are null.
Am I doing something wrong here or have I encountered a bug?
-Edit-
Made it clear that I'm using Autofac.
-Edit 2-
Adding more detail.
My implementation of the IMemberViewModel class has various properties on it, including an observable object called current member. It is declared as below:
public class MemberViewModel : ViewModelBase, IMemberViewModel
{
…
(see constructor above)
…
public MemberDisplay CurrentMember =>
m_CurrentMember ?? (m_CurrentMember = new MemberDisplay())
On the implementation of IMemberViewModel I have a method that sets the various properties on CurrentMember.
The order of operations is this:
The end user taps an image for a member. This fires a command on the (theoretically) singleton instance of the IMemberViewModel implementation. This command executes an async task that awaits an async call to the API to load the data for that member. After that data is loaded and the properties set on CurrentMember, the app navigates to the profile screen. The profile screen resolves IMemberViewModel (per above).
Expected Behavior:
The properties on CurrentMember from the resolved instance of IMemberViewModel are set to the values that have just been set from the load data method. This expectation arises from assuming that there is a single instance of IMemberViewModel.
Actual Behavior:
The CurrentMember's properties are at their default values, i.e. string.Empty, 0, null, etc.
The odd thing here is that this doesn't happen to every model. I have a message model that I am resolving in the same manner on the same screen and it seems to be fine.
This issue turned out to be caused by the way we were going about initializing everything. For posterity's sake, I will give a brief breakdown of what was happening and what I did to prevent it.
Previous App Flow:
App opens & constructor is called. This calls into the initialization routine above.
User logs in.
First instance of IMemberViewModel resolved using static container.
A message pops up asking the user for Push Notifications Permissions
When this happens, the app OnSleep is called (iOS)
After the user selects an answer, OnResume is called.
OnResume calls initialization routine
New container created.
Call to load data happens on old container, new pages reference new container.
Issue arises as described above.
Correction to the flow:
First, from what I can tell the init calls do not need to be made on resume and/or start if made in the app constructor. If the app is "killed" because other apps need the memory space, a fresh version of the app will be created on next launch (see the Android Activity Lifecycle and the iOS App Lifecycle).
Second, because I'm paranoid and because it can't hurt, in the app init routine I am now checking to determine whether the container exists and whether the interface is already registered.
public static void Init(ISetup setup)
{
if (Container != null && IsModelRegistered()) return;
RegisterDependencies(setup);
…
}
private static bool IsModelRegistered()
{
return Container.IsRegistered<IMemberViewModel>();
}

Using singleton WCSession delegate instead of instance methods

I'm experiencing a strange issue with WatchOS (but I suppose that this problem is similar with iOS and OSX).
I'm using a singleton to handle a WCSession delegate (The full code is by NatashaTheRobot, I paste here only a portion of her code, the full code is here ).
This class has a startSession function where the singleton is associated as delegate of the session:
func startSession() {
session?.delegate = self
session?.activateSession()
}
and all the delegate functions are defined inside the same class, like session:didReceiveMessage:replyHandler:
I'd like to be able to have the delegate called every time that the Watch app receives a message independently by the current InterfaceController.
I thought that a good place to achieve this goal might be the ExtensionDelegate class:
class ExtensionDelegate: NSObject, WKExtensionDelegate {
let session = WatchSessionManager.sharedManager // THE SINGLETON INSTANCE
func applicationDidFinishLaunching() {
session.startSession()
}
it seems that this code is not working and the delegate function are never called.
Then I decided to go for a less generic way and I started adding the reference to the singleton instance inside all the InterfaceController... but again it doesn't work and delegate methods are never been called.
Then, in my last attempt, I've implemented the session delegate protocol directly inside the InterfaceController code. In that case I receive the messages from the iOS app... it was working correctly (obviously only when the watch app is presenting that specific InterfaceController).
My question are: why implementing a generic singleton object doesn't work? Why I have to implement the delegate directly on the InterfaceController to make it work?
Try moving the startSession call from the ExtensionController's applicationDidFinishLaunching to its init method. The init gets called no matter which context (complication, app, glance, notification, etc) the extension is being loaded for.

Getting the right syntax for SignalR server to call client

I'm putting together a very basic sort of "hello world" app with SignalR, with the minor caveat that it's self-hosted, which introduces an additional wrinkle or two. Basically, I'm trying to figure out the right way to call methods on my client(s) from the server.
On my client, for instance, I've got a method that looks like this:
roomHub.onEcho = function (msg) {
console.log("onEcho called: " + msg);
};
And I can call it successfully from my server-side hub like so:
public class RoomHub : Hub
{
public void Echo(string echo)
{
Clients.onEcho(echo);
}
}
And it works, but of course, it calls all the clients, not just one. And in the various samples I've seen online (e.g., https://github.com/SignalR/SignalR/blob/master/samples/Microsoft.AspNet.SignalR.Hosting.AspNet.Samples/Hubs/Benchmark/HubBench.cs, I see all sorts of commands that make it look like I should be able to specify who gets called, e.g.:
public void Echo(string echo)
{
Clients.Caller.onEcho(echo);
Clients.Caller(Context.ConnectionId).onEcho(echo);
Clients.All.onEcho(echo);
}
But I can't get any of the above syntaxes to work. For Clients.All.onEcho() and Clients.Caller.onEcho(), absolutely nothing happens. For Clients.Caller(Context.ConnectionId).onEcho(), Firebug tells me that it's actually trying to call a Caller() method on my JavaScript roomHub instance, which of course isn't there.
Here's the weird bit, though. If I look at the Hub class, I can see why none of these work - because the Hub constructor overrides a bunch of the properties of its "Clients" object with NullClientProxies:
protected Hub()
{
Clients = new HubConnectionContext();
Clients.All = new NullClientProxy();
Clients.Others = new NullClientProxy();
Clients.Caller = new NullClientProxy();
}
But I'm kinda mystified as to why it does that - or why the samples seem to work anyway - or what the expected approach should be.
Any thoughts? What am I doing wrong here?
We've been updating docs recently so you've probably seen lots of inconsistent data around the place. The latest version of SignalR is 1.0 alpha2 ( http://weblogs.asp.net/davidfowler/archive/2012/11/11/microsoft-asp-net-signalr.aspx ). All of the documentation has been updated to show the new syntax so if you're using an older version, please upgrade. Check out the wiki for examples https://github.com/SignalR/SignalR/wiki/Hubs

Unit Test & Log4net

I have unit test testing an action in my controller, the action writes to log4net.
When I run my action it works well - writes to log4net .
However , When I run the unit test - the action doesn't write to log4net but doesn't throw any exception.
Does anyone have a solution?
// ARRANGE
var memoryAppender = new MemoryAppender();
BasicConfigurator.Configure(memoryAppender);
// ACT
_sut.DoWhatever();
// ASSERT - using xunit - change the expression to fit your purposes
Assert.True(memoryAppender.GetEvents().Any(le => le.Level == Level.Warn), "Expected warning messages in the logs");
You don't need to add in another layer of indirection by using a logging interface (if you don't want to). I have used the abstracted way for years, but now am moving towards just using the MemoryAppender as it is testing what is actually happening. Just be sure to .Clear() the appender after each test.
Log4net does not throw exceptions: http://logging.apache.org/log4net/release/faq.html
Writing to an log on disk or in a database in a unit test is counterproductive; the whole point is automation. You shouldn't have to check the logs every time you run tests.
If you truly need to verify that a call was made to log something, you should mock the ILog interface and assert that the appropriate method was called.
If you are using a mocking framework, this is trivial. If you aren't, you can create a TestLogger class that implements or partially implements ILog and exposes extra properties that show how many times a given method was called. Your assertions will check that the methods were called as expected.
Here is an example of a class to be tested:
public class MyComponent
{
private readonly ILog _log;
public MyComponent(ILog log)
{
_log = log;
}
public string DoSomething(int arg)
{
_log.InfoFormat("Argument was [{0}]", arg);
return arg.ToString();
}
}
and the test (using Rhino.Mocks to mock the ILog):
[TestClass]
public class MyComponentTests
{
[TestMethod]
public void DoSomethingTest()
{
var logger = MockRepository.GenerateStub<ILog>();
var component = new MyComponent(logger);
var result = component.DoSomething(8);
Assert.AreEqual("8", result);
logger.AssertWasCalled(l => l.InfoFormat(Arg<string>.Is.Anything, Arg<int>.Is.Equal(8)));
}
}
Try adding:
[assembly: log4net.Config.XmlConfigurator()]
To the AssemblyInfo.cs (or init log4net any other way).
Or try using AssemblyInitialize as suggested in this answer.
It is your log4net configuration. Right now it might be in your web.config or log4net.config file in the web/bin. You have to place it in a common location and make it discoverable by both web app and test. Or you have to put it into your unittest.project=>app.config file. But if you have many test projects, it would be duplicated in number of places. So the ideal would be to put it in a common place.
Here's another possible solution if none of the other solutions work for you...
Try writing your log file to the root of the c drive. By default, I set log4net to write to the current directory which is always the directory the unit test is running from right?... wrong! I'm running windows 8 with vs 2012 using MS Unit Test, and it writes the file to a local temp directory which gets deleted after the unit test completes. In my setup it writes the file to here:
C:\Users\[myself]\AppData\Local\Temp\TestResults
Bottom line, any unit tests I write for now on, are going to use a full absolute log file path and not a relative one.

Resources