For example:
[TestFixtureSetUp]
public void Init()
{
GetTestRepo(false);
}
[TestFixtureSetUp] in this example, what does it do? From my experience, [] usually refers to lists.
Attributes. They are a way to add metadata about methods/properties/interfaces/classes/namespaces for inspection at runtime.
Your example adds the TestFixtureSetUpAttribute to a method. This allows the test runner to determine which method in your class to run when setting up a text fixture.
The test runner loads your test assembly into memory at runtime. It then enumerates through the classes defined within your assembly that have been marked with a particular attribute (whatever NUnit uses to mark a test class). The runner now knows what classes to instantiate to run tests. It then looks through the methods defined in the class for a method that will be run to set up the test fixture. It searches each method for the attribute you asked about. Once it finds that method it knows to run that method before running tests/each test (whichever it means in NUnit).
Attributes are all about adding information about a method that you can search for at runtime. Its the kind of thing where if you don't need 'em you don't miss 'em, but when you DO need 'em OMFG is it great that they're available.
(In C#, you can omit the "Attribute" from the type name. The compiler knows you're talking about, for instance, "SerializableAttribute" when you say [Serializable])
Attributes. You can find more information here.
It is an Attribute
It's an attribute. Sort of like MetaData for the class/function you use it on.
They are called attributes (analogous to Java annotations) and they are compiled in as meta data.
You appear to be recreating a basic VB/C# faq by asking one question at a time in SO. To add to that, it does appear to be a good way to get reputation.
To answer the TITLE, [] are the symbols used to
index into arrays
enclose an attribute (metadata) on a method
one other thing I can't remember
VB.Net uses the <> characters for the same purpose on metadata, but uses () to indicate array access.
Java uses a leading "#" for the same purpose
If you didn't have those special characters, the compiler couldn't interpret what you wrote. Not sure what else you want to know. Do you want to know the meaning of TestFixture?
Related
quick theoric question. I have the following code:
if (partnership != null && partnership.UseCustomNotifier)
{
//some behavior
}
else
{
Integration.Protocol.Client.Notifier protocolNotifier = new Integration.Protocol.Client.Notifier();
}
I have two implementations for partnership that are chosen using reflection. Integration.Protocol is not in the usings. Implementation should be chosen dynamically; thing is, if I comment that last line (the instantiation of protocolNotifier), it will only chose one implementation (the one that does not come from the Integration.Protocol, because is the only one available). Otherwise, it will be chosen dynamically using reflection.
I know that this code sucks (I've improved it already), but I was curious on why this behavior was ocurring. I would guess that when the solution compiles before running, it checks that line where protocolNotifier is instantiated and adds the using on compilation time. Is this correct? Does it only happen within the scope of the method? Or the whole class? I am curious on how the .NET compiler works in those situations.
If I understand you correctly:
partnership is an object of a type that is chosen by using reflection to find all available classes with that name (we'll call it Partnership) and creating an object of the found type
The Integration.Protocol namespace has a class called Partnership (or whatever it's actually called), but there is also another class called Partnership in either this project's code or some other library that you're already using elsewhere
Depending on if you include that last line or not, your reflection code picks one or the other
If I'm correct in that, then I believe the behaviour you're seeing is simply because it's loading the Integration.Protocol library (assuming that is a separate DLL and not actually part of the current project code).
If you show us the code of how you set partnership, then we can confirm this. But if I'm correct, then if you don't use Integration.Protocol in that last line, then that library simply isn't loaded, and your reflection code won't find anything from that library.
It's not that "adding the using on compilation time", because using statements just allow you to not include the namespace when referring to classes. It doesn't have anything to do with whether libraries are loaded at runtime or not.
I have the following test:
[Fact]
public void StartProgram_CallsZoneProgramStart()
{
var zone = A.Fake<Zone>();
zone.StartProgram();
A.CallTo(() => zone.ZoneProgram.Start(null, A.Dummy<ActionBlock<InterruptInfo>>())).MustHaveHappened(Repeated.Exactly.Once);
}
It's creating a dummy of type ActionBlock<InterruptInfo> which is being passed into the MustHaveHappened call. zone.StartProgram definitely calles the zone.ZoneProgram.Start method, but this call is not seen by FakeItEasy. It returns the following error message:
Assertion failed for the following call:
ZoneLighting.ZoneProgramNS.ZoneProgram.Start(<NULL>, ActionBlock\`1 Id=1)
Expected to find it exactly once but found it #0 times among the calls:
1: ZoneLighting.ZoneProgramNS.ZoneProgram.Start(inputStartingValues: Faked ZoneLighting.ZoneProgramNS.InputStartingValues, interruptQueue: ActionBlock`1 Id=2)
2: ZoneLighting.ZoneProgramNS.ZoneProgram.Start(inputStartingValues: <NULL>, interruptQueue: ActionBlock`1 Id=2)
As can be seen from the error message, the ID on the ActionBlocks being compared are different (1 and 2), which is why it's not able to see that the call is made. My question is, why is the ID of the dummied ActionBlock = 1? I thought being a dummy object, it shouldn't have any concrete details in it like ID etc. Is this because generic types cannot be dummied?
I saw something similar here: https://github.com/FakeItEasy/FakeItEasy/issues/402
But I wasn't able to figure out if that's talking about the same thing or not. Any help would be greatly appreciated.
I am not familiar with ActionBlocks, so am not sure where they get their Id values from, but I think I can shed some light on what's going on in your test.
First, I think you're confused about what a Dummy is. If so, don't feel bad. They can be a little confusing. From the Dummy documentation, a Dummy is
Dummy is an object that FakeItEasy can provide when an object of a certain type is required, but the actual behavior of the object is not important.
They are mostly used by FakeItEasy itself when it needs to create an object to feed to class constructors (we'll see more about that later), or when it needs to return a non-fakeable object from a method or property. It's rare for end users to have to create them.
A Dummy is an actual object (it has to be—otherwise, how could we do anything with it?). It has to have whatever concrete details in it that its type has (in this case, ActionBlock<InterruptInfo>). There are no restrictions against Dummying generic types.
Looking at the docs for how a Dummy is made, we can see that since ActionBlock<InterruptInfo> probably doesn't have a custom IDummyDefinition available (do you have one?), and it's not a Task, and it's not fakeable (because the class is sealed), then the Dummy is made by invoking one of the ActionBlock constructors, with Dummies being made to satifsy each of the arguments.
I guess that ActionBlocks have IDs. How they're assigned, I have no idea, but if they're a good ID, then it looks like we have two different ActionBlock<InterruptInfo>s: one provided in zone.StartProgram, and the Dummy made in the test.
The ActionBlocks documentation suggests that it doesn't override Equals, so a reference comparison will be performed, and the two ActionBlocks (the Dummy and the one used in the production code) don't match. This is why FakeItEasy doesn't recognize the call.
If you were just trying to see if any call to zone.ZoneProgram.Start was made with the first argument null and the second argument some ActionBlock, I think you might've meant to use:
A.CallTo(() => zone.ZoneProgram.Start(null, A<ActionBlock<InterruptInfo>>.Ignored))
.MustHaveHappened(Repeated.Exactly.Once);
(Ignored can also be shortened to _. Read more about ignoring argument values if you're so inclined.)
That may get you past your immediate problem, although I have concerns about two things:
It looks like zone.ZoneProgram.Start is being called twice, not "Exactly.Once", but I'm sure you'll be able to deal with this, and
In general, faking the object under test is considered to be an anti-pattern. Typically one supplies fake dependencies to the production code under test. I'm not saying it won't work, but sometimes it can lead to confusion. Still, it may be a problem for another day, after the current question has been resolved.
I hope that helps a little.
Oh, and you asked about Issue 402. That issue is about giving users more power when defining customization classes that will control how dummies are created. Unless you've made a class extending IDummyDefinition or DummyDefinition, it's probably not relevant at this point.
Multiple enumeration of the same enumerable is something that has been a performance problem for us, so we try to stomp those warnings in the code. But there is a generic extension function that we have for throwing null parameter exceptions that generates a lot of these warnings. Its signature looks like this:
public static void VerifyArgumentIsNotNull<T>(this T value, string valueName) where T : class
All it does is check for null and throw a nicely formatted and localized (for whichever human language is in play at the time) exception.
When this function is used on an IEnumerable parameter, it makes the code analysis warn about a possible multiple iteration of the IEnumerable because the analyzer has no idea what that function does.
I would like to put some tag on this function that says, "Yes, this takes the enumerable as an input, but it does not iterate it and therefore should not be counted as a possible iteration by callers." Is there any such tag? I've searched the Internet to no avail.
Yes, what you're asking is very much possible, but requires a little work. ReSharper uses Code Annotations to add hints to its analysis engine and make more sense of the code it has to work with. I recently recorded a webinar with JetBrains called ReSharper Secrets, where I go into much greater detail about what Annotations are and how to use them. You should watch it!
There's an annotation attribute, [NoEnumeration] that does exactly what you ask - specifies that the given IEnumerable argument is not enumerated, however it's not included in the default Code Annotation Attributes, however it is defined in the JetBrains.Annotations.dll assembly.
So after this introduction, here's what you need to do:
(if you haven't already,) go to ReSharper Options, then Code Inspection → Code Annotations, and press the Copy default implementation to clipboard button
Create a file in any of your (shared) projects called Annotations.cs (or any other name)
Paste the code from the clipboard, completely replacing anything that was previously in Annotations.cs
Add the following definition at the end of the file:
Code:
/// <summary>
/// Indicates that IEnumarable, passed as parameter, is not enumerated.
/// </summary>
[AttributeUsage(AttributeTargets.Parameter)]
public sealed class NoEnumerationAttribute : Attribute
{
}
After you done this, all that's left to do is place the [NoEnumeration] attribute on the value argument, like this:
public static void VerifyArgumentIsNotNull<T>([NoEnumeration] this T value, string valueName) where T : class
{
....
}
And that's it! The warning will disappear!
Bonus:
There are 3 additional attributes you can use to decorate this method to make it even more useful: [NotNull], [ContractAnnotation] and [InvokerParameterName]. I recently describe what they do (and a short demo) in this issue for a similar API called LiteGuard.
Annotations are fun :)
Since VerifyArgumentIsNotNull is generic, but does nothing type specific, it can take an object:
public static void VerifyArgumentIsNotNull(this object #object, string argumentName) { ... }
Resharper (9.11.) assumes that the called method does not cast #object back to an IEnumerable, and thus there is no warning.
Note the lack of the class constraint means the compiler may not warn if you accidentally pass a value type to VerifyArgumentIsNotNull, but Resharper will warn that a value type can never be null.
This approach has the additional advantage of saving the JIT from creating an instance (closed generic) method for every type that VerifyArgumentIsNotNull is called with; a micro-optimization to be sure, but a rare example where a generic may not be preferable to an old-school object.
One possible drawback to the above: I have seen similar implementations where VerifyArgumentIsNotNull returns "value". In this case a return value of type T is needed to avoid an explicit cast. (IMO this syntax is ugly. So it is not a drawback for me.)
Two other editorial comments:
1. A method name I have seen: ThrowIfNull is more concise, and "Throw" is more explicit than "Verify"
2. I no longer use methods for this, because without an annotation on VerifyArgumentIsNotNull Resharper must assume the argument could still be null. I find it much simpler to let R#, insert a 1-line if + throw when I add the NotNullAttribute.
This approach does not work for the broader case where you want to ensure that a method is called with an enumerable. In this case Igal Tabachnik's additions to Annotations are great.
Assuming you are using Visual Studio 2013/2012 (I'm only aware of this feature in 2013 though) in the code analysis window you should be able to right click the message navigate to Suppress Message > In Source File or In Suppression File
Alternatively you can achieve the same effect by clicking the action drop down of the message in the Code Analysis window.
I have fields in one class and I want to move them to another class. Creating the new fields is not that much work. Changing all their references from the class they were in until now, however - is.
‘Rename’ doesn’t accept ‘myClass.Field’ as valid. Is changing using Find-and-Replace the only option (though then I’ll have to check every occurrence because of identically-named variables)? Or is there a simple way like ‘Rename’?
There is no (built-in) refactoring that will move a variable to another type. Some third party refactoring tools (such as Resharper) do include this as additional features.
However, I would recommend letting the compiler help you instead of relying on Find and Replace. If you remove the original variables, every access of the variable will become an instant compiler error. This will give you all of the usages without false positives.
Here is what I would do:
1. Ensure everything compiles well first :)
2. Move your variable into the new class MyClass
3. Add a field MyClass myClass to the original class and instantiate it in the constructor
4. Using a text editor (as VS does not allow this) search for all instances of Field and replace them by myClass.Field
5. Back to VS, compile your code again
This should work fine and should save you some valuable time.
Regards,
R# 4.5 (answers to 5 are welcome)
VS2008 (answers to VS2010 are welcome)
C# (FWIW)
I'm using a constructor (the question applies for methods, too), and there's Intellisense:
I don't yet have a value to specify for this first parameter, "firstName". Today, I type "firstName", then let the IDE create that variable for me (which I initialize to some value).
I understand that the IDE will create the variable for me. I want it to create the variable name for me.
I don't want to have to type "firstName". I like the variable name the parameter author chose, and I want to use that variable name in my (calling) code.
Is there a way to have these acceptable variable names re-generated for me (the calling code) automatically as I move, parameter by parameter, through this line of (calling) code?
You may get close to what you are looking for with VS2010.
Type p.Foo(
This will open the description of the currently selected constructor, out of the list of all constructors. If you type a letter, or hit ctrl + space, intellisense auto completion will open.
A difference here between VS2008 and VS2010 is named parameters. In VS2010, your completion list will have entries for the named parameters firstName: and lastName:.
Type the first letter of the parameter name (what you are referring to as "the variable name the parameter author chose")
Intellisense should jump straight to that entry, and allow you to do completion the same way it usually does.
Type a space, enter, or comma
Intellisense it will insert the identifier used for the named parameter. It won't insert the colon (unless you type it), so you don't have to use the named parameter feature to accomplish your goal here. You can just take advantage of the fact that the text you are looking for is in your completion list.
How you get Visual Studio to actually generate the local variables (which, according to your question, it seems like you have already solved) baffles me, and would be up to you to take care of :) If you've got that second problem licked, I'd like to know how, too.
You can make a code snippet that creates the variable and inserts it as parameters.
MSDN Reference on snippets
I don't understand your scenario entirely but I'm assuming you want to inject a variable name from calling assembly into the called code. if so, you may want to look into System.CodeDom that lets you create class and its memebers during runtime beside plethora of other functionality it offers.
I am pretty sure you can do it with Resharper or CodeRush/Refactor.
It sounds like to me that what your trying to do is get out of typing at all! To have the IDE put the code in you intend so you don't have to. A quite lofty goal - with the exception that you'd put us all out of work ;-(
All fun aside, what you're probably reaching for is a code gen tool such as the T4 Toolbox ( one of my new favorite toys). If you're looking for a tool that will auto-generate your code snippets as you type, that's a tall order. The nearest thing available would be Resharper.
Here is an example of a class constructor I generated from my customization of T4 Toolbox templates:
public partial class EvaluationController : SmartController
{
private readonly IEvaluationService _evaluationSvc;
private readonly IEvaluationMapper _evaluationMapper;
private readonly IEvaluationCriterionMapper _evaluationCriterionMapper;
private readonly IParticipantEvaluationMapper _participantEvaluationMapper;
public EvaluationController( IEvaluationRepository repository, IEvaluationService evaluationSvc, IEvaluationMapper evaluationMapper, IEvaluationCriterionMapper evaluationCriterion, IParticipantEvaluationMapper participantEvaluation)
{// : base(repository, evaluationMapper)
_evaluationSvc = evaluationSvc;
_evaluationMapper = evaluationMapper;
_evaluationCriterionMapper = evaluationCriterion;
_participantEvaluationMapper = participantEvaluation;
}
If that is what you're after, the place to start would be: http://t4toolbox.codeplex.com/
I've got an example project where I use customizations of the templates to spin up my business classes, various methods & repository layer.http://t4tarantino.codeplex.com/
There's an example of the level of complexity of output you can generate at
http://geekswithblogs.net/JamesFleming/archive/2010/08/18/code-generation-with-t4-toolbox.aspx
HTH