I'm trying to see if Moq is something I'd like to use in a new project as the other mocking frameworks I've used are challenging IMHO. So for instance, I have a method as such:
IEnumerable<PickList> GetPickLists();
I'm not sure how I'm supposed to mock this... I've tried something like this, but I'm getting compliation errors (I know the following
Returns() isn't correct, but can't figure out what to put in the Returns body:
var mockCrm = new Mock<ICrmProvider>();
mockCrm.Setup<IEnumerable<PickList>>(foo => foo.GetPickLists())
.Returns<IEnumerable<PickList>>({});
Also, trying to mock something like these two methods:
CustomerSyncResult ApplyActions(IEnumerable<CustomerAction> actions);
IEnumerable<Customer> GetCustomers(IEnumerable<string> crmIDs, IEnumerable<string> emails);
I know I'm asking a blanket question, but I'm having a heck of a time getting started. The CHM in the download doesn't have enough samples for me and some of the tutorials out there seem to be using obsolete methods as well as not covering enumerations which makes it tricky for me :(
Any tips would be greatly appreciated.
Try
mockCrm.Setup(x => x.GetPickLists())
.Returns(new List<PickList>());
The QuickStart is a good reference.
Some examples for the other methods:
mockCrm.Setup(x => x.ApplyActions(It.IsAny<IEnumerable>()))
.Returns(new CustomerSyncResult());
mockCrm.Setup(x => x.GetCustomers(It.IsAny<IEnumerable>(),
It.IsAny<IEnumerable>()))
.Returns(new List<Customers>());
As an aside, make the IEnumerable generic in your original interface for better type safety.
You can also use the new Moq v4 functional specifications:
var list = new List<PickList> { new PickList() };
ICrmProvider crm =
Mock.Of<ICrmProvider>(
x =>
x.GetPickLists() == list);
That is not as well documented currently. Note that you no longer have to write mock.Object. Some links:
Old style imperative mocks vs moq functional specifications
Moq Discussions: Mock.Of - how to specify behavior?
The exact syntax (using It.Is, the contents of the lists, etc.) will depend on what you're trying to accomplish. It.IsAny will match any argument, which will make things easier when dealing with sequence or collection parameters.
Related
I have a dotnet core application.
My Startup.cs registers types/implementations in Autofac.
One of my registrations needs previous access to a service.
var containerBuilder = new ContainerBuilder();
containerBuilder.RegisterSettingsReaders(); // this makes available a ISettingsReader<string> that I can use to read my appsettings.json
containerBuilder.RegisterMyInfrastructureService(options =>
{
options.Username = "foo" //this should come from appsettings
});
containerBuilder.Populate(services);
var applicationContainer = containerBuilder.Build();
The dilemma is, by the time I have to .RegisterMyInfrastructureService I need to have available the ISettingsReader<string> that was registered just before (Autofac container hasn't been built yet).
I was reading about registering with callback to execute something after the autofac container has been built. So I could do something like this:
builder.RegisterBuildCallback(c =>
{
var stringReader = c.Resolve<ISettingsReader<string>>();
var usernameValue = stringReader.GetValue("Username");
//now I have my username "foo", but I want to continue registering things! Like the following:
containerBuilder.RegisterMyInfrastructureService(options =>
{
options.Username = usernameValue
});
//now what? again build?
});
but the problem is that after I want to use the service not to do something like starting a service or similar but to continue registering things that required the settings I am now able to provide.
Can I simply call again builder.Build() at the end of my callback so that the container is simply rebuilt without any issue? This seems a bit strange because the builder was already built (that's why the callback was executed).
What's the best way to deal with this dilemma with autofac?
UPDATE 1: I read that things like builder.Update() are now obsolete because containers should be immutable. Which confirms my suspicion that building a container, adding more registrations and building again is not a good practice.
In other words, I can understand that using a register build callback should not be used to register additional things. But then, the question remain: how to deal with these issues?
This discussion issue explains a lot including ways to work around having to update the container. I'll summarize here, but there is a lot of information in that issue that doesn't make sense to try and replicate all over.
Be familiar with all the ways you can register components and pass parameters. Don't forget about things like resolved parameters, modules that can dynamically put parameters in place, and so on.
Lambda registrations solve almost every one of these issues we've seen. If you need to register something that provides configuration and then, later, use that configuration as part of a different registration - lambdas will be huge.
Consider intermediate interfaces like creating an IUsernameProvider that is backed by ISettingsReader<string>. The IUsernameProvider could be the lambda (resolve some settings, read a particular one, etc.) and then the downstream components could take an IUsernameProvider directly.
These sorts of questions are hard to answer because there are a lot of ways to work around having to build/rebuild/re-rebuild the container if you take advantage of things like lambdas and parameters - there's no "best practice" because it always depends on your app and your needs.
Me, personally, I will usually start with the lambda approach.
Upgrading AngleSharp from 0.9.6 to 0.9.9 I have this line of code no longer compiling:
return configuration.With(LoaderService(new[] { requester }));
It complains that LoaderService does not exist in the current context. So what happened to LoaderService? Is there a replacement? Does it still exist but just somewhere else?
Good question. Sorry for being late to the party, but even though you may have solved your problem someone else is having a hard time figuring it out.
LoaderService was essentially just a helper to create a loader. But having a service for anything creating a little thing would be overkill and not scale much. Also AngleSharp.Core would need to define all these. So, instead a generic mechanism was introduced, which allows registering such "creator services" via Func<IBrowsingContext, TService>.
However, to solve your piece of code I guess the following line would do the trick:
return configuration.WithDefaultLoader(requesters: requester);
This registers the default loader creator services (one for documents, one for resources inside documents) with the default options (options involve some middleware etc.).
Under the hood (besides some other things) the following is happening:
// just one example, config.Filter is created based on the passed in options
return configuration.With<IDocumentLoader>(ctx => new DocumentLoader(ctx, config.Filter));
I am developing a metro application and I want to create some async operations whose my own classes would implement.
I have found just examples of async using WinRT operations (e.g. CreateFileAsync). I do not find any intance where someone is creating a async method and consuming it.
Now you can do it. Look at this:
http://blogs.msdn.com/b/nativeconcurrency/archive/2011/10/27/try-it-now-use-ppl-to-produce-windows-8-asynchronous-operations.aspx
http://code.msdn.microsoft.com/Windows-8-Asynchronous-08009a0d
WinRT Async Production using C++
Use create_async in C++:
IAsyncOperationWithProgress<IBuffer^, unsigned int>^ RandomAccessStream::ReadAsync(IBuffer^ buffer, unsigned int count, InputStreamOptions options)
{
if (buffer == nullptr)
throw ref new InvalidArgumentException;
auto taskProvider = [=](progress_reporter<unsigned int> progress, cancellation_token token)
{
return ReadBytesAsync(buffer, count, token, progress, options);
};
return create_async(taskProvider);
}
Use AsyncInfo.Run in .NET:
public IAsyncOperation<IInfo> Async()
{
return AsyncInfo.Run(_ =>
Task.Run<AType>(async () =>
{
return await DoAsync();
})
);
}
I posted the same question in Microsoft forums and they gave me two replies. The first was:
Hi Claudio,
In the Developer Preview there isn't an easy way to create your own
async operations. We are aware of this shortcoming and are trying to
solve it for the next pubic release. In the meanwhile, you could
design your API as async and we will provide guidance on how to
convert sync to async.
Thanks
Raman Sharma, Visual C++
When I asked for the hard way to do this, another guy, someone responsible for PPL said me:
We’re planning to do a refresh of the sample pack we released a few
weeks ago and add a few samples on creation of async operations. I
expect that it will happen in a couple of weeks or so. If you keep an
eye on our blog at http://blogs.msdn.com/b/nativeconcurrency, you’ll
be the first to know.
As to how hard it is... The general-purpose solution that we’re
contemplating is about 1000 lines of C++ code making copious use of
template metaprogramming. Most of it will be in the header file so you
can explore it yourself. While a less general solution can be less
complex, you will still need to implement a base class, do the state
management, error handling etc. At this moment I can’t go into more
detail, but I will say that you will love how easy it is to author
async operations with PPL – so hang in there!
Artur Laksberg PPL team
Then, there is no solution at that time. Thank you all.
Yes, see Ben Kuhn's //BUILD/ talk: http://channel9.msdn.com/events/BUILD/BUILD2011/PLAT-203T He shows how to build an asynchronous API.
At the current time, there is no good solution for high level (C++/WX) classes. However if you use the low level C++ interfaces, you can use the WRL::AsyncBase class to help build your async interfaces.
Here is documentation about the AsyncBase class.
It is confusing, but there is a difference between WinRT C++ code and WRL. You can use WRL to code to the ABI layer directly. WRL does not use exceptions, but loves templates. The recommend coding style for WinRT is not the same as WRL.
I am not sure if everyone can do this, but using WRL you in general need to implement a class that inherits:
class CreateAysncOp: public RuntimeClass<IAsyncOperation<result_runtime_class*>,AsyncBase<IAsyncCompletedHandler<result_runtime_class*>>
{
...
Then you can use
hr = MakeAndInitialize<CreateAsyncOp, IAsyncOperation<type_foo*>>(...);
C++ WinRT is now the best way to implement WinRT async methods. This uses co_await and co_return, new C++ language features (in the process of standardization). Read the docs on this page.
I'm parallelizing some back-end code and trying not to break interfaces. We have several methods that return Dictionary and internally, I'm using ConcurrentDictionary to perform Parallel operations on.
What's the best way to return Dictionary from these?
This feels almost too simple:
return myConcurrentDictionary.ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
I feel like I'm missing something.
Constructing the Dictionary<K,V> directly will be slightly more efficient than calling ToDictionary. The constructor will pre-allocate the target dictionary to the correct size and won't need to resize on-the-fly as it goes along.
return new Dictionary<K,V>(myConcurrentDictionary);
If your ConcurrentDictionary<K,V> uses a custom IEqualityComparer<K> then you'll probably want to pass that into the constructor too.
Nope. This is completely fine. .NET sequences are just nice like that. :D
I'm in my module file. I want to define some complex variables for use throughout the module. For simple things, I'm doing this:
function mymodule_init() {
define('SOME_CONSTANT', 'foo bar');
}
But that won't work for more complex structures. Here are some ideas that I've thought of:
global:
function mymodule_init() {
$GLOBALS['mymodule_var'] = array('foo' => 'bar');
}
variable_set:
function mymodule_init() {
variable_set('mymodule_var', array('foo' => 'bar'));
}
property of a module class:
class MyModule {
static $var = array('foo' => 'bar');
}
Variable_set/_get seems like the most "drupal" way, but I'm drawn toward the class setup. Are there any drawbacks to that? Any other approaches out there?
I haven't seen any one storing static values that are array objects.
For simple values the drupal way is to put a define in the begining of a modules .module file. This file is loaded when the module is activated so that is enough. No point in putting it in the hook_init function.
variable_set stores the value in the database so don't run it over and over. Instead you could put it in your hook_install to define them once. variable_set is good to use if the value can be changed in an admin section but it's not the best choice to store a static variable since you will need a query to fetch it.
I think all of those methods would work. I have never used it in this fashion, but I believe the context module (http://drupal.org/project/context) also has its own API for storing variables in a static cache. You may want to check out the documentation for the module.
It's always a good practice to avoid globals. So that makes your choice a bit easier.
If you err towards a class, you'll be writing code that is not consistent with the D6 standards. There are a lot of modules that do it but I personally like to keep close to the Drupal core so I can understand it better. And code that's written in different styles through the same application can have an adverse effect on productivity and maintenance.
variable_set() and define() are quite different. Use the former when you can expect that information to change (a variable). Use the latter for constants. Your requirements should be clear as which one to use.
Don't worry too much about hitting the database for variable_set/get. If your software is written well, it should not effect performance hardly at all. Performance work arounds like that should only be implemented if your applications has serious performance issues and you've tried everything else.