Visual Studio 2010 and Test Driven Development - visual-studio

I'm making my first steps in Test Driven Development with Visual Studio. I have some questions regarding how to implement generic classes with VS 2010.
First, let's say I want to implement my own version of an ArrayList.
I start by creating the following test (I'm using in this case MSTest):
[TestMethod]
public void Add_10_Items_Remove_10_Items_Check_Size_Is_Zero() {
var myArrayList = new MyArrayList<int>();
for (int i = 0; i < 10; ++i) {
myArrayList.Add(i);
}
for (int i = 0; i < 10; ++i) {
myArrayList.RemoveAt(0); //should this mean RemoveAt(int) or RemoveAt(T)?
//VS doesn't know. Any work arounds?
}
int expected = 0;
int actual = myArrayList.Size;
Assert.AreEqual(expected, actual);
}
I'm using VS 2010 ability to hit
ctrl + .
and have it implement classes/methods on the go.
I have been getting some trouble when implementing generic classes. For example, when I define an .Add(10) method, VS doesn't know if I intend a generic method(as the class is generic) or an Add(int number) method. Is there any way to differentiate this?
The same can happen with return types. Let's assume I'm implementing a MyStack stack and I want to test if after I push and element and pop it, the stack is still empty. We all know pop should return something, but usually, the code of this test shouldn't care for it. Visual Studio would then think that pop is a void method, which in fact is not what one would want. How to deal with this? For each method, should I start by making tests that are "very specific" such as is obvious the method should return something so I don't get this kind of ambiguity? Even if not using the result, should I have something like int popValue = myStack.Pop() ?
How should I do tests to generic classes? Only test with one generic kind of type? I have been using ints, as they are easy to use, but should I also test with different kinds of objects? How do you usually approach this?
I see there is a popular tool called TestDriven for .NET. With VS 2010 release, is it still useful, or a lot of its features are now part of VS 2010, rendering it kinda useless?
Whenever I define a new property in my test code, and ask VS to generate that method stub for me, it generates both a getter and a setter. If I have something like int val = MyClass.MyProperty i'd like to to understand that (at least yet) I only want to define a getter.
Thanks

I see there is a popular tool called TestDriven for .NET. With VS 2010 release, is it still useful, or a lot of its features are now part of VS 2010, rendering it kinda useless?
It's still useful in case you use one of a number of different unit testing frameworks (nunit, mbunit, xunit, csunit, etc).
There are also other tools (like Visual Nunit) that provide visual studio integration for running unit tests.

To your code sample, why would you have a method RemoveAt(T obj)?
You can do RemoveAt(int index) and Remove(T obj) instead. Take a look at Microsoft's APIs (for example, for List<T>) that see how they set up the Remove methods for a generic collection.
And now for your points:
1: What would Add(int number) do? If I understand your intentions correctly, Add(10) can only be intepreted as "Add value 10 at the end of my collection". If you wanted to add a value at a particular index, you can (and probably should) name that method Insert: Insert(int index, T value).
2: sure, Visual Studio will interpret the method as void at first, but you can edit it to be something like
public class MyStack<T>
{
public T Pop()
{
}
}
The stubs built by pressing Ctrl+. are a convenience, but not gospel. You don't HAVE to always assign a return value to a variable. If you don't need it in a test, don't do it. If you want VS to pick up on a return type other than void, you can write a different unit test (e.g. that Pop() returns the last pushed value).
3: I'd test with the types that I see most frequently used in my code. If you're writing a public API, then test with as many types as possible. If you're using NUnit, look into using the [TestCase] attribute to help you avoid writing some duplicate code.
4: I still use TestDriven, but I haven't tried going without it, so I can't really make a useful comparison.
5: Just delete the setter if you don't need it. Some addon frameworks like ReSharper support more advanced code generation, including read-only properties.

Related

Visual Studio: capture object state in debug mode and use it in unit test

Is there an easy and elegant way to capture objects in debug mode and just dump them in the unit tests?
I am using some very large object (like 30+ fields) and i would need that as data in my unit tests.
I don't know of any quick-and-easy way of doing this and, in fact, I suspect that the whole issue with field/properties, nesting, private-public prevents VS from providing a general-purpose solution for this.
You could certainly use serialization, for example calling some {{MyHelper.ToInitExpression()}} in the Immediate window while debugging and then taking the clipboard data and putting it into your unit tests. To make the initialization expression you would need to use reflection to find out what properties/fields there are and what their current values are. If you have nested objects, you'll need to take care of those too.
An alternative, if you go the ReSharper route, is to generate some sort of ToInit() method. You would need to make these individually for each of the classes you need. This is rather easy using ReSharper's generator infrastructure. Feel free to ping me (skype:dmitri.nesteruk) if you need help with this.
The other alternative is to simply hand-craft such methods, for example:
public static string ToAssemblyCode(this DateTime self)
{
var sb = new StringBuilder("new System.DateTime(");
sb.AppendFormat("{0},{1},{2}", self.Year, self.Month, self.Day);
if (self.Hour != 0 || self.Minute != 0 || self.Second != 0)
sb.AppendFormat(",{0},{1},{2}", self.Hour, self.Minute, self.Second);
if (self.Millisecond != 0)
sb.AppendFormat(",{0}", self.Millisecond);
sb.Append(")");
return sb.ToString();
}
You can try use IntelliDebugger plugin for Visaul Studio to create snapshot of any variable during debugging. The IntelliDebugger allows you to save and then to compare object with other objects of same type.
Desired object is stored in XML-format on disk (<YourSolution>\_IntelliDebugger.<YourSolution>\ExpressionSnapshots folder). I designed this feature to compare the state of objects during debugging. Perhaps it will be useful for writing unit-test or we can improve it for this case.
Note: IntelliDebugger is currently in beta and have limitations. We are open to any questions and feature requests to make it more effective for you.

Writing a Unit Test to ensure dynamic proxy creation by testing for IEntityWithChangeTracker (EF4)

I've been working through Julie Lerman's books on Entity Framework, and I've run into somewhat of a snag...
In "Programming Entity Framework DbContext" on page 66 Julie suggests writing a Unit Test to make sure that dynamic proxies are being created, since the requirements for getting Entity Framework to create change tracking proxies are fairly simple, but also very easy to miss.
With that being said, I followed the general structure of Julie's example to write the following test for my code:
[Test]
public void IsDynamicProxy()
{
using (var scienceFairToGoContext = new ScienceFairToGoContext())
{
var scienceFair = scienceFairToGoContext.ScienceFairs.Create();
Assert.IsTrue(scienceFair is IEntityWithChangeTracker);
}
}
When I hover over the scienceFair object its pretty obvious its a change tracking proxy
System.Data.Entity.DynamicProxies.ScienceFair_D3C57A2F699E75F716E63553D950EF7EC75F0C603F69093FCD78122CC0D6452C
...but whenever I run the unit test it always fails because "scienceFair is IEntityWithChangeTracker" always evaluates to false.
It appears as though someone else ran into this issue as well and posted it to the O'Reilly forums, but there doesn't seem to be a solution posted, nor do my Google searches return any type of answer.
I'm currently using Visual Studio 2010, EF4, NUnit, and running my tests through ReSharper. It's also worth mentioning that if run the code in a simple console application and debug it I get the same results.
Actually, it looks like I figured out the issue. While working through Julie's book, I thought it would be a good idea to have all of the entities inherit from a base class, ScienceFairToGoEntity.
It looks like I forgot to mark the 4 properties I had on the base class (InsertBy, InsertDate, UpdateBy, UpdateDate) as virtual, so the dynamic proxies were for Lazy Loading/ Relationship Fix-up and not for Change Tracking.
It's weird to find this non-working piece of code in such a good book. You can however execute you test by:
using (var scienceFairToGoContext = new ScienceFairToGoContext())
{
var scienceFair = scienceFairToGoContext.ScienceFairs.Create();
Assert.IsTrue(scienceFair.GetType().IsSubclassOf(typeof(ScienceFair)));
}
although it is less generally applicable when there are entities in inheritance hierarchies. With derived entities you'd have to use
scienceFairToGoContext.BaseEntities.Create<TDerivedEntity>()

Can I do Unit Testing for non-void methods with ReSharper?

I tried to research on how to do unit testing with ReSharper for C# on Visual Studio for methods that are non void types, but to no avail. ReSharper only detects void methods.
Is there any way to reduce writing a void method to call the other methods with a return type? In this way, it can reduce time spent and increase efficiency.
My friend wants to do it without requiring much effort to generate the code, which also means that he does not need to write th eI know it can be done.
I tried looking through the 'Options' for ReSharper in changing the method type to allow non-void methods, but still am unable to find.
Can anyone explain to me if it this is possible/not possible?
Thank you so much : )
What version of ReShaper are you using? And what test-framework are you using?
I user ReShaper 5.1 and NUnit and this for example works for me:
[TestCase(true, Result="contentArea-wide")]
[TestCase(false, Result="contentArea")]
public string LoadView_PopulateContent_ContentCssClassIsSet(bool hideLeftNavigation) {
var mvpFaker = this.CreateMvpFaker().CreatePresenter();
mvpFaker.View.HideLeftNavigation = hideLeftNavigation;
mvpFaker.LoadView();
return mvpFaker.Model.Content.CssClass;
}
Is that the thing you want to do?

Hand Coding a Coded UI Test

I have been working with Coded UI Test(CUIT) feature of VS2010 .
When recording the CodedUI framework generates a lots of hierarchical classes.
I was wondering whether coding(by hand) a CUIT would reduce the code created and would it be as optimized(in searching elements) as generated code??
Also what are the scenarios where a CUIT could be coded by hand?
CUITe (Coded UI Test enhanced) Framework is for people who prefer hand coding.
http://cuite.codeplex.com/
CUITe is a thin layer developed on top of Microsoft Visual Studio Team Test's Coded UI Test engine which helps reduce code, increases readability and maintainability, while also providing a bunch of cool features for the automation engineer.
CUITe allows you to define a much simpler Object Repository (== UIMap). Each page/window will be defined in a separate class file, and each UI control definition will be just a one liner. You can move common controls to a parent class which increases maintainability. You can also categorize the page/window definition classes into different folders as you deem fit.
I have been working on Coded UI, from my understanding recorded/generated code is too complex and difficult to maintain.
I always use hand coding, which is simple and easy to maintain.
Here is full sample hand coded UI script for Silver-light application
[TestMethod]
public void SilverlightHANDCODINGTest()
{
BrowserWindow br = BrowserWindow.Launch(#"http://localhost:1377/SilverlightApplication1TestPage.html");
UITestControl sCustom = new UITestControl(br);
sCustom.TechnologyName = "Web";
sCustom.SearchProperties.Add("ControlType", "Custom");
sCustom.SearchProperties.Add("TagName", "OBJECT");
sCustom.SearchProperties.Add("Type", "application/x-silverlight-2");
sCustom.SearchProperties.Add("TagName", "OBJECT");
// sCustom.DrawHighlight();
SilverlightControl sframe = new SilverlightControl(sCustom);
sframe.TechnologyName = "Silverlight";
sframe.SearchProperties.Add(SilverlightControl.PropertyNames.MaxDepth, "-1");
sframe.DrawHighlight();
SilverlightEdit sTextBox = new SilverlightEdit(sCustom);
sTextBox.TechnologyName = "Silverlight";
sTextBox.DrawHighlight();
Playback.Wait(2000);
sTextBox.SetProperty(SilverlightEdit.PropertyNames.Text, "Thank god");
SilverlightButton sButton = new SilverlightButton(sCustom);
sButton.TechnologyName = "Silverlight";
sButton.SearchProperties.Add(SilverlightButton.PropertyNames.DisplayText, "Button");
sButton.DrawHighlight();
Playback.Wait(2000);
Mouse.Click(sButton);
SilverlightComboBox sComboBox= new SilverlightComboBox(sCustom);
sComboBox.TechnologyName = "Silverlight";
sComboBox.DrawHighlight();
Playback.Wait(2000);
sComboBox.SetProperty(SilverlightComboBox.PropertyNames.SelectedItem,"Kishore");
}
Thanks,
You may hand write less code but its going to likely be less maintainable and more prone to breaking. You can use the partial class to effectively override the search clauses after the code has been generated.

How good idea is it to use code contracts in Visual Studio 2010 Professional (ie. no static checking) for class libraries?

I create class libraries, some which are used by others around the world, and now that I'm starting to use Visual Studio 2010 I'm wondering how good idea it is for me to switch to using code contracts, instead of regular old-style if-statements.
ie. instead of this:
if (fileName == null)
throw new ArgumentNullException("fileName");
use this:
Contract.Requires(fileName != null);
The reason I'm asking is that I know that the static checker is not available to me, so I'm a bit nervous about some assumptions that I make, that the compiler cannot verify. This might lead to the class library not compiling for someone that downloads it, when they have the static checker. This, coupled with the fact that I cannot even reproduce the problem, would make it tiresome to fix, and I would gather that it doesn't speak volumes to the quality of my class library if it seemingly doesn't even compile out of the box.
So I have a few questions:
Is the static checker on by default if you have access to it? Or is there a setting I need to switch on in the class library (and since I don't have the static checker, I won't)
Are my fears unwarranted? Is the above scenario a real problem?
Any advice would be welcome.
Edit: Let me clarify what I mean.
Let's say I have the following method in a class:
public void LogToFile(string fileName, string message)
{
Contracts.Requires(fileName != null);
// log to the file here
}
and then I have this code:
public void Log(string message)
{
var targetProvider = IoC.Resolve<IFileLogTargetProvider>();
var fileName = targetProvider.GetTargetFileName();
LogToFile(fileName, message);
}
Now, here, IoC kicks in, resolves some "random" class, that provides me with a filename. Let's say that for this library, there is no possible way that I can get back a class that won't give me a non-null filename, however, due to the nature of the IoC call, the static analysis is unable to verify this, and thus might assume that a possible value could be null.
Hence, the static analysis might conclude that there is a risk of the LogToFile method being called with a null argument, and thus fail to build.
I understand that I can add assumptions to the code, saying that the compiler should take it as given that the fileName I get back from that method will never be null, but if I don't have the static analyzer (VS2010 Professional), the above code would compile for me, and thus I might leave this as a sleeping bug for someone with Ultimate to find. In other words, there would be no compile-time warning that there might be a problem here, so I might release the library as-is.
So is this a real scenario and problem?
When both your LogToFile and Log methods are part of your library, it is possible that your Log method will not compile, once you turn on the static checker. This of course will also happen when you supply code to others that compile your code using the static checker. However, as far as I know, your client's static checker will not validate the internals of the assembly you ship. It will statically check their own code against the public API of your assembly. So as long as you just ship the DLL, you'd be okay.
Of course there is a change of shipping a library that has a very annoying API for users that actually have the static checker enabled, so I think it is advisable to only ship your library with the contract definitions, if you tested the usability of the API both with and without the static checker.
Please be warned about changing the existing if (cond) throw ex calls to Contracts.Requires(cond) calls for public API calls that you have already shipped in a previous release. Note that the Requires method throws a different exception (a RequiresViolationException if I recall correctly) than what you'd normally throw (a ArgumentException). In that situation, use the Contract.Requires overload. This way your API interface stays unchanged.
First, the static checker is really (as I understand it) only available in the ultimate/academic editions - so unless everyone in your organization uses it they may not be warned if they are potentially violating an invariant.
Second, while the static analysis is impressive it cannot always find all paths that may lead to violation of the invariant. However, the good news here is that the Requires contract is retained at runtime - it is processed in an IL-transformation step - so the check exists at both compile time and runtime. In this way it is equivalent (but superior) to a regular if() check.
You can read more about the runtime rewriting that code contract compilation performs here, you can also read the detailed manual here.
EDIT: Based on what I can glean from the manual, I suspect the situation you describe is indeed possible. However, I thought that these would be warninings rather than compilation errors - and you can suppress them using System.Diagnostics.CodeAnalysis.SuppressMessage(). Consumers of your code who have the static verifier can also mark specific cases to be ignored - but that could certainly be inconvenient if there are a lot of them. I will try to find some time later today to put together a definitive test of your scenario (I don't have access to the static verifier at the moment).
There's an excellent blog here that is almost exclusively dedicated to code contracts which (if you haven't yet seen) may have some content that interests you.
No; the static analyzer will never prevent compilation from succeeding (unless it crashes!).
The static analyzer will warn you about unproven pre-/post-conditions, but doesn't stop compilation.

Resources