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

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?

Related

Hint or infer the return type for RSpec let() implementing FactoryGirl create()

Using RubyMine, in an rspec test, is there a way to let RubyMine know the type of the created object (for auto-completion and 'cannot find ' warning suppression?
eg:
# #yieldreturn [Tibbees::Tibbee]
let!(:tibbee) {
create(:tibbee,
canonical_vendible: article_vendible,
owner: tibbee_user)
}
RubyMine doesn't seem to recognise #yieldreturn (and I'm not sure if that's correct anyhow) and I've had no luck with #type and #return.
The
let!(:tibbee) { create(...) || Tibbees::Tibbee.new }
cludge works, but yuk. Any advice greatly appreciated. Perhaps there's even a way to let the factories take care of it, but that seems 'too deep' an abstraction to be likely to be picked up by RubyMine?
Not an immediate solution, but:
While google on this, I came across https://github.com/JetBrains/ruby-type-inference which holds great promise for the future, that is probably relevant to anyone with an interest in this question.
From the README:
ruby-type-inference project is a completely new approach to tackle the problems Ruby dynamic nature by providing more reliable symbol resolution and type inference.
In answer to some questions I asked them:
We are going to make the plugin working and publicly available with 2017.3 release though it will definitely be in "beta" since several problems are yet to be solved even on the theoretical side. For everything to work real properly we have to rework our type system on IDE side which is most likely not going to be completed in 2017.
It might be run at the moment, however ... the results are more of experimental value ... [and] it will be difficult to use it on a daily basis.
This is an old request, but updating for future reference with discussion at https://youtrack.jetbrains.com/issue/RUBY-19907:
As of today (RubyMine 2021.2.3, Build #RM-212.5457.52) Rubymine can now introspect the correct type for FactoryBot create within a let, so that:
let(:name) { create(:some_model)} now has the type inferred correct from the factory.
However it would still be useful to be able to annotate a let that can't be introspected (maybe it's not calling FactoryBot).
But the suggestion of #yieldreturn seems wrong - that's for methods that take a block. But it would be nice if you could annotate let(:whatever){} with #return tag. Compare https://rubydoc.info/gems/yard/file/docs/Tags.md#yieldreturn with https://rubydoc.info/gems/yard/file/docs/Tags.md#return

Visual Studio 2010 and Test Driven Development

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.

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.

Cross Theaded Calls - Many controls Heavy GUI Application after .net 1.1 2.0 upgrade- best way?

I have recently upgraded a .net1.1 solution to .net2.0.
AS this is a very heavy GUI appilcation with loads of controls and many multithreaded operations that update the GUI.
While these operations worked seamlessly in .net1.1 it is throwing up Cross Threaded Illegal operations after the upgrade.
Considering the fact that tehre are numerous grids, buttons and status labels that need to be updated via these multi threaded operations, I decided to code for checking the InvokeRequired solution, however doing that for every control would probably not be the best way to go about it.
I was wondering if you could suggest a better way of how I can go about it or propose any OOPS based class structure that I could code around to make the code look better.
Please do let me know if my question is unclear.
Thanks in advance
Here's a good article about your problem:
http://www.perceler.com/articles1.php?art=crossthreads1
The quick and dirty hack is to disable the check altogether:
static class Extensions {
public static DisableCrossThreadCheck(this Control c){
c.CheckForIllegalCrossThreadedCalls = false;
foreach(var ctl in c.Controls) {
ctl.DisableCrossThreadCheck();
}
}
}
(in your form):
this.DisableCrossThreadCheck();

Detecting recursive properties

Does anyone know if there is some option in VS2010 or some third party tool that I can use to detect recursive properties such as:
private string name;
public string Name
{
get{ return this.Name; }
}
The above is obviously an error, but the compiler offers no warnings. I can appreciate that, in general, recursive methods are perfectly legal, but the above scenario does not make much sense. In fact it happens when I write the property before the backing field, even when writing this.name in lower case, because VS2010 will see that this.name does not exist and change the casing to this.Name which does exist.
The problem gets worse when binding to that property in WPF. The application crashes and takes VS2010 with it. That makes it very hard to debug, which is why I would love to have a tool of some kind that would alert me at compile time.
Hope someone can help.
/Klaus
I know that ReSharper adds a column indicator next to a recursive call so that's easy to see. I don't think it has the option to find all recursive methods in your code though. ReSharper 5.0 EAP is available for VS2010.

Resources