How to create a unit test class - unit-testing

I inherited a solution with 4 projects: Front-End Project, Business Project, Data Project and a Test Project.
The test project is quite... let's say empty... and now after I changed a few things on some searches methods of the business class I would like to generate some tests to validate the changes i've made.
So my question is: Is there a automatic way to generate a "empty frame test class" to test my actual code? Something like "right click the class you want to test and click generate test class and choose the project where it will be created" maybe?!?
Details:
I'm using VS 2012 Ultimate
There's no tests for the class I'm working on

There is built in functionality that allows you to create unit test classes. I am not sure if that also works in combination with NUnit though.
Anyway, I never used it. What I do is:
add a test class to the test project
decorate the class with the [TestFixture] attribute
write the first method of what I want to test
decorate the method with the [Test] attribute
write the test
and start the TDD cycle.
A typical test class skeleton will look like this
using NUnit.Framework;
namespace Tests.Framework
{
[TestFixture]
public class SomeClassTests
{
[Test]
public void AMeaningfulTestMethodName()
{
// the test
}
}
}
I also have Resharper at my aid so that I can run the test from visual studio straight away.
Since it's so little effort for me to add a new test fixture to the project, I don't see the need of adding it via templates. The most annoying part of templates is that they overgenerate. Templates will generate [SetUp] and [TearDown] fixtures which I don't always need. I like to keep my classes as clean as possible. But it's a matter of taste.
Here are some links that you might find helpful if you want to:
save your own predefined test class template
want to use the built in functionality of visual studio
follow a msdn walkthrough regarding the topic

Related

How to configure unit testing for AnyLogic agent code?

How do you configure unit testing framework to help develop code that is part of AnyLogic agents?
To have a suitable test driven development rhythm, I need to be able to run all tests in a few seconds. I thought of exporting the project as a standalone application (jar) each time, but that's pretty slow.
I thought of trying to write all the code outside AnyLogic in separate classes, but there are many references to built-in AnyLogic classes, as well as various agents. My code would need to refer to these somehow, and I'm not sure how to do that except by writing the code inside AnyLogic.
I wonder if there's a way of adding the test runner as a dependency, and executing that test runner from within AnyLogic.
Does anyone have a setup that works nicely?
This definitely requires some advanced Java, but testing, especially unit testing is too often neglected in building good robust models. I hope this simple example is enough to get you (and lots of other modellers) going.
For Junit testing, we make use of two libraries that you can add as a dependency to your model.
Now there are two main types of logic that you will want to test in simulation models.
Functions in Java classes
Model execution
Type 1: Suppose I have this very simple Java class
public class MyClass {
public MyClass() {
}
public boolean getResult() {
return true;
}
}
And I want to test the function getResult()
I can simply create a new class and create a function that I annotate with the #Test modifier and then also make use of the assertEquals() method, which is standard in junit testing
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class MyTestClass{
#Test
public void testMyClassFunction1() {
boolean result = new MyClass().getResult();
assertEquals("The value of the test class 1", result, true);
}
Now comes the AnyLogic specific implementation (there are other ways to do this but this is the easiest/most useful, you will see in a minute)
You need to create a custom experiment
Now if you run this from the Run Model button you will get this output
SUCCESS
Run: 1
Failed: 0
You can obviously update and change the output as to your liking
Type 2: Suppose we have this very simple model
And the function getResult() simply returns an int of 2.
Now we need to create another custom experiment to run this model
And then we can write a test to run this Custom Experiment and check the result
Simply add the following to your MyTestClass
#Test
public void testMyClassFunction2() {
int result = new SingleRun(null).runExperiment();
assertEquals("Value of a single run", result, 2);
}
And now if you run the RunAllTests customer experiment it will give you this output
SUCCESS
Run: 2
Failed: 0
This is just the beginning, you can read up tons on using junit to your advantage

Visual Studio 2013: Creating ordered tests

Can someone suggest a way to run tests in a specific order in Visual Studio 2013 Express?
Is there a way to create a playlist for the tests, which also defines the order in which to run them?
By the way: These are functional tests, using Selenium, written as unit tests in C#/Visual Studio. Not actual unit tests. Sometimes a regression test suite is so big it takes a while to run through all the tests. In these cases, I've often seen the need to run the test in a prioritized order. Or, there can be cases where it's difficult to run some tests without some other tests having been run before. In this regard, it's a bit more complicated than straight unit tests (which is the reason why it's normally done by test professionals, while unit tests are done by developers).
I've organised the tests in classes with related test methods. Ex.: All login tests are in a class called LoginTests, etc.
Class LoginTests:
- AdminCanLogin (...)
- UserCanLogin (...)
- IncorrectLoginFails (...)
- ...
CreatePostTests
- CanCreateEmptyPost (...)
- CanCreateBasicPost (...)
...
These classes are unit test classes, in their own project. They in turn calls classes and methods in a class library that uses Selenium.
MS suggests creating an "Ordered Unit Test" project. However, this is not available in the Express edition.
To address your playlist request directly see MS article: http://msdn.microsoft.com/en-us/library/hh270865.aspx Resharper also has a nice test play list tool as well.
Here is an article on how to setup Ordered Tests but you cannot use this feature with Express as it requires Visual Studio Ultimate, Visual Studio Premium, Visual Studio Test Professional. http://msdn.microsoft.com/en-us/library/ms182631.aspx
If you need them ordered then they are more then likely integration tests. I am assuming you would like them ordered so you can either prepare data for the test or tear data back down after the test.
There are several ways to accommodate this requirement if it is the case. Using MSTest there are 4 attributes for this you can see more details of when they are executed here http://blogs.msdn.com/b/nnaderi/archive/2007/02/17/explaining-execution-order.aspx.
My other suggestion would be to have a helper class to preform the tasks(not tests) you are looking to have done in order, to be clear this class would not be a test class just a normal class with common functionality that would be called from within your tests.
If you need a test to create a product so another test can use that product and test that it can be added to a shopping cart then I would create a "SetupProduct" method that would do this for you as I am sure you would be testing various things that would require a product. This would prevent you from having test dependencies.
With that said, integration tests are good to verify end to end processes but where possible and applicable it might be easier to mock some or all dependencies such as your repositories. I use the Moq framework and find it really easy to work with.
This code is from the blog post linked above, I am placing it here in case the link ever dies.
Here is an example of a test class using the setup / tear down attributes to help with your tests.
[TestClass]
public class VSTSClass1
{
private TestContext testContextInstance;
public TestContext TestContext
{
get
{
return testContextInstance;
}
set
{
testContextInstance = value;
}
}
[ClassInitialize]
public static void ClassSetup(TestContext a)
{
Console.WriteLine("Class Setup");
}
[TestInitialize]
public void TestInit()
{
Console.WriteLine("Test Init");
}
[TestMethod]
public void Test1()
{
Console.WriteLine("Test1");
}
[TestMethod]
public void Test2()
{
Console.WriteLine("Test2");
}
[TestMethod]
public void Test3()
{
Console.WriteLine("Test3");
}
[TestCleanup]
public void TestCleanUp()
{
Console.WriteLine("TestCleanUp");
}
[ClassCleanup]
public static void ClassCleanUp()
{
Console.WriteLine("ClassCleanUp");
}
}
Here is the order that the methods were fired.
Class Setup
Test Init
Test1
TestCleanUp
Test Init
Test2
TestCleanUp
Test Init
Test3
TestCleanUp
ClassCleanUp
If you give more information on what you are trying to accomplish I would be happy to assist you in when to use which attribute or when to use the help class, note the helper class is NOT a test class just a standard class that has methods you can utilize to do common tasks that may be needed for multiple tests.

Can I make Intellij Idea 11 IDE aware of assertEquals and other JUnit methods in Grails 2.0.x unit tests?

I find it very odd that with such excellent Grails integration, Idea does not recognize standard JUnit assertion methods in Grails unit tests. I created a brand new project and made one domain class with corresponding test to make sure it wasn't something weird with my larger project. Even if I add a #Test annotation, the IDE does not see any assertion methods
#TestFor(SomeDomain)
class SomeDomainTests {
#Test //thought adding this, not needed for Grails tests, would help but it doesn't
void testSomething() {
assertEquals("something", 1, 1); //test runs fine, but IDE thinks this method and any similar ones don't exist
}
}
I have created an issue in IntelliJ bugtracker: http://youtrack.jetbrains.com/issue/IDEA-82790. It will be fixed in IDEA 11.1.0
As workaround you can add "import static org.junit.Assert.*" to imports.
Note: using "assert 1 == 1 : 'message'" is preferable than "assertEquals('message', 1, 1)" in groovy code.
Idea has problems if you use 'def' to define a variable (so it's type is not known) and then you try to pass it to a Java method which is strongly typed. Because it can't infer the type.
So it will give a message with words to the effect of "there is no method assertEquals() that takes arguments with type String, null, null".
I wouldn't expect this message in the example you give (because you are using ints directly, not a dynamically-typed variable) but I thought you might have missed it when trying to create a simple example code snippet for the question.
With the #TestFor annotation an AST will add methods to you test class and IDEA does not catch these methods.
You have two options:
Make the test class extends GrailsUnitTestCase.
Add dynamic method to your test class.

using IProvideDynamicTestMethods for silverlight 4 unit tests

Has anyone had any lucking creating their custom test class and using the IProvideDynamicTestMethods interface? I have a case where I need to dynamically generate test methods and this seems to be what I need. I goal is to have test methods generated based on some files I am testing.
Jeff Wilcox mentions this as a new feature in SL3 ( http://www.jeff.wilcox.name/2008/09/rc0-new-test-features/ , see the dynamic test methods section), but I was unable to find any examples of this.
I don't know how to register my custom test class (it inherits from ITestClass). I looked at the SL4 unit testing source to see how the test class are discovered and I found the following in UnitTestFrameworkAssembly.cs source link
/// <summary>
/// Reflect and retrieve the test class metadata wrappers for
/// the test assembly.
/// </summary>
/// <returns>Returns a collection of test class metadata
/// interface objects.</returns>
public ICollection<ITestClass> GetTestClasses()
{
ICollection<Type> classes = ReflectionUtility.GetTypesWithAttribute(_assembly, ProviderAttributes.TestClass);
List<ITestClass> tests = new List<ITestClass>(classes.Count);
foreach (Type type in classes)
{
tests.Add(new TestClass(this, type));
}
return tests;
}
It looks like it will always use the built-in TestClass.
Am I missing something? I don't how to get the test framework to use my custom TestClass
Any pointers appreciated.
Thanks
It looks like the only way to set this up right now is to write your own UnitTestProvider for the test runner. The good thing is the code is available, so it's not too hard to do this.
You can either grab the code from the default Vstt from codeplex here and make any changes you you like to it. I'm still experimenting with this right now, so lets see how this goes. I got this idea by looking at this github project.
The key was to plug in your own provider, which was done in Raven.Tests.Silverlight.UnitTestProvider.Example/App.xaml.cs.
Hope this helps someone

Why I can't add generic class to silverlight unit test project?

I have little problem here.
I have two projects for Windows Phone 7.
One is regular Client appliacation and second is Test project.
Test project can be normal executed. But when i add generic class:
public class Class1<T>
{
}
Then test execution ends with
Information: Tag expression "All" is in use.
TestInfrastructure: All
TestExecution: Unit Testing
A first chance exception of type 'System.NotSupportedException' occurred in mscorlib.dll
TestExecution: TestGroupLifestyleClient.Test starting
No test is executed. On emulator (or device) appear only "test assemblies" (no test names, no nothing).
When I remove the <T> part from class it works normaly again.
I've encountered the same problem when mocking/stubbing the functionality of a generic class that my unit tests rely on. If the generic class isn't a test class (i.e. annotated [TestClass]) then a work around is to create this generic class in another project in your Visual Studio solution and then make the project with your unit tests reference this new project. The generic class will then be accessible to your tests and runnable.
My solution structure given below
= Solution 'MobileApp'
- MobileAppProject
- TestProject
- TestSupportProject
Cheers,
Alasdair.