Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I need help on the unit testing. I have never done a code unit test through Visual studio and can't seem to find any videos or reading material on how to create one using just Visual Studio 2010 Professional. Everything I find is in reference in one way or another to testing center and I don't have it, nor can I get a full version of it (broke student).
When I try to d a unit test i see all this extra stuff generated and I don't understand any of it, I can tell that some of it has to be updated after generated but don't know to what for the given situation. Is there any free resource that i can use that will tell me how to make a unit test? I would even be happy learning how to make them from scratch.
First thing to understand is that a unit test in C# is created and run with a reference to a library which supports unit testing. Microsoft provide MSTest, and there are alternatives. A very popular one is NUnit.
Most test frameworks work with attributes. An attribute in this context is the bit which decorates the code using square brackets:
[ThisIsAnAttribute]
public void ThisMethodIsDecoratedWithAnAttribute(){}
Attributes provide additional information which can be retrieved at runtime using reflection. Reflection allows you to inspect the structure of the code and types in that code.
Most testing frameworks use two main concepts. 1) A "Fixture" which is a snazzy way of saying "A set of tests" and 2) a "Test". A fixture is represented by a class with a fixture attribute, tests are represented by methods with a test attribute.
The tests are obviously testing something, so you need two things here as well. 1) The thing you are testing and 2) A way to "Assert" that the test has passed or failed.
So the thing you are testing is just code. Generally this should be a small bit of code which is independent and isolated. Tests should never really be longer than 20 lines max (although remember to never say never).
To Assert that a test has passed or failed you use a class from the testing framework which feeds back test success. This is usually called Assert and is static.
So to assert that a value at the end of a test is a certain value, you might say:
Assert.IsEqualTo(5, myResultVariable);
The Assert class has a lot of methods. These will test for various conditions. Is it null, is it equal to, is it not equal to, that sort of thing.
To run the test, you use the framework's runner. This will take the code and report back the results.
So here's a simple MSTest unit test.
[TestClass]
public class MathTestsForSimpleOperators
{
[TestMethod]
public void TestThatAdding3To8Equals11()
{
Assert.AreEqual(11, 3 + 8);
}
}
You can see the fixture is called MathTestsForSimpleOperators (Be descriptive) and it has one test called TestThatAdding3To8Equals11. It's not a useful test, but it has all the parts you need.
Here is a link to NUnit's getting started page. MSTest is just as simple to use. It will take you through step by step installing, writing and running a test.
NUnit getting started page
http://code.tutsplus.com/articles/the-beginners-guide-to-unit-testing-what-is-unit-testing--wp-25728
Maybe?
Another suggestion, try doing thins your self, and when you are stuck just don't hestitate to ask this community. But don't just ask for whole help to your projects.
Poom
Related
Requirement: If any file has protection(Sensitivity label) then we are throwing an error message.
Before we go and do our actual implementation, I want to achieve this using TDD approach.
Please let me clarify whether the below steps can we achieve using unit test with C#?
Is it possible to write unit test on this MIP? If yes,
Through program , I want to read the file(.pdf or office app files) and apply sensitivity label before using MIP Code.
Once it reaches MIP code snippet ,this should detect this file and it has protection.
If it is protected then should throw an error message or else skip the execution.
I never used the MIP SDK, but you are in the wrong path if you want to test the file information using MIP.
1. Use double testing
First you will have to use Double Testing (a stub or a fake) to be sure that you business rules are applied correctly in your algorithme (throwing the exception if the sensitivity level is bad for example)
The stub or the fake will allow you to control the sensitivity level return, It's also means that you will have to wrap the "MIP Library" inside a class or using IOC
2. Use integration testing
When you will have a first working scenario with you unit test, you will be able to make the same with Integration Testing. You will add to your project the material to have a "production environnement" adding files with differents sentivities to your test project
Conclusion
Of course, I know that my answer is not a working solution but your needs is not simple and cannot be set in a stackoverflow post.
You will need to investigate about double testing & integration testing before making any development if you want to have reliable unit tests.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
I am rewriting a C# .NET project and currently planning how I am going to do the testing.
After everything I have read I will install the XUnit framework (for the first time -- I am more experienced with MSTest). Now I am wondering whether I should combine it with FluentAssertions (which I also never used before) or rather write pure XUnit tests.
At a first glance, FluentAssertions sounds nerdy and stylish, but I'm not sure if it really will lead me to write best-readable code and how well it will scale over complex tests.
Hence I am searching for your experience and arguments. [When] (do | would) you use FluentAssertions? I'm curious.
Fluent is mostly about readability and convenience.
If you are going to write more than a handful of unit test I'd suggest using it.
I recently had the case where I was mapping object 'a' and 'b' onto object 'c' and I wanted to verify the mapper with a unit test.
So, I created an 'expectedObject' which contained all properties that object 'c' should contain once it was mapped.
As I had not written a comparer, nor did I have the need for one, it would have been very cumbersome to compare object 'c' with 'expectedObject' to assert they contain the same data. The object in question contained many properties which in turn had many properties.
But with Fluent I could simply write
c.Should().BeEquivalentTo(expectedObject);
This is much easier to read than a litany of Assert.AreEqual() and in this case, more importantly, much faster to write as well.
Fluent Assertions is a Nuget package I've been using consistently on
my projects for about 6 years. It's extremely simple to pick-up and
start using. Most people can get to grips with it within 5-10 minutes
and it will make reading your unit tests a little bit easier. Fluent
Assertions is free so there really isn't a party foul for trying it
out. I think I've introduced Fluent Assertions to over 10 teams now
and so far no one's complained. The biggest reason why most teams
don't use it is just lack of exposure to it. Using a standard approach
a unit test may look similar to this:
[TestMethod]
public void Example_test()
{
var actual = PerformLogic();
var expected = true;
Assert.AreEqual(expected, actual);
}
There's nothing wrong with this test but you need to spend a second or
two to understand what's going on. Instead, using FLuent Assertations
you can write the same test like this:
[TestMethod]
public void Example_test()
{
var result = PerformLogic();
result.Should().BeTrue();
}
Hopefully, you can see that the second example takes a lot less time
to read, as it reads like a sentence rather than an Assert statement.
Fundamentally, this is all Fluent Assertions is, a number of extension
methods that make it easier to read your unit tests compared to Assert
statements. I'm hoping you can understand why it's so easy to pick up.
All you need to do is get the outcome of your test in a result
variable, use the Should() exertion and then use Fluent Assertions
other extensions to test for your use case. Simple!
http://www.jondjones.com/c-sharp-bootcamp/tdd/fluent-assertions/what-is-fluent-assertions-and-should-i-be-using-it
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I want to keep myself as short as possible:
First: I read related posts, but they didn't help a lot.
See: What is a quality real world example of TDD in action?
Or: How do you do TDD in a non-trivial application?
Or: TDD in ASP.NET MVC: where to start?
Background:
I'm not a total TDD beginner, I know the principles
I read Rob C Martin and MC Feathers and the like
TDD works fine for me in Bowling and TicTacToe Games
But I'm kind of lost when I want to to TDD in my workplace. It's not about Mocking, I kinda do know how to mock the dependecies.
It's more:
WHEN do I code WHAT?
WHERE do I begin?
And: WHEN and HOW do I implement the "database" or "file system" code. It's cool to mock it but at integration test stage I need id as real code.
Imagine this (example):
Write a program which reads a list of all customers from a database.
Related to the customer IDs it has to search data from a csv/Excel file.
Then the business logic does magic to it.
At the end the results are written to the database (different table).
I never found a TDD example for an application like that.
EDIT:
How would you as a programmer would implement this example in TDD style?
PS: I'm not talking about db-unit testing or gui unit testing.
You could start without a database entirely. Just write an interface with the most basic method to retrieve the customers
public interface ICustomerHandler
{
List<Customer> GetCustomers(int customerId);
}
Then, using your mocking framework, mock that interface while writing a test for a method that will use and refer to an implementation of the interface. Create new classes along the way as needed (Customer, for instance), this makes you think about which properties are required.
[TestMethod()]
public void CreateCustomerRelationsTest()
{
var manager = new CustomerManager(MockRepository.GenerateMock<ICustomerHandler>());
var result = manager.CreateCustomerRelations();
Assert.AreEqual(1, result.HappyCustomers);
Assert.AreEqual(0, result.UnhappyCustomers);
}
Writing this bogus test tells you what classes are needed, like a CustomerManager class which has a method CreateCustomerRelations and two properties. The method should refer to the GetCustomer method in the interface, using the instance of the mock that was being injected in the class constructor.
Do just enough to make the project build and let you run the test for the first time, which will fail as there's no logic in the method being tested. However, you are off on a great start with letting the test dictate which input your method should take, and what output it should receive and assert. Defining the test conditions first helps you in creating a good design. Soon you will have enough code written to ensure the test confirms your method is well designed and behaves the way you want it to.
Think about what behaviour you are testing, and use this to drive a single higher level test. Then as you implement this functionality use TDD to drive out the behaviour you want in the classes you need to implement this functionality.
In your example I'd start with a simple no-op situation. (I'll write it in BDD langauge but you could similarly implement this in code)
Given there are no customers in the database
When I read customers and process the related data from the csv file
Then no data should be written to the database
This sort of test will allow you to get some of the basic functionality and interfaces in place without having to implement anything in your mocks (apart from maybe checking that you are not calling the code to do the final write)
Then I'd move on to a slightly wider example
Given there are some customers in the database
But none of these customers are in the CSV file
When I read customers and process the related data from the csv file
Then no data should be written to the database
And I would keep adding incrementally and adjusting the classes needed to do this, initially probably using mocks but eventually working up to using the real database interactions.
I'd be wary of writing a test for every class though. This can make your tests brittle and they can need changing every time you make a small refactoring like change. focus on the behaviour, not the implementation
your flow should be something like this:
I've written a class and want to test if it works well. For now I think the best way to do it is to create new console application referencing main project, then make new instance of my class and mess with it. This approach unlike others enables IntelliSense, using keywords (no full names for classes) and Debugging.
Anyone knows how to do it in more convenient way to do this without making new console app?
Using a console app to test your class is what I would call a "poor man's unit test."
You are on the right track in wanting to do this sort of testing and I (and most others on SO) would suggest using a unit testing framework of some sort to help you out. (Mocking may be important and useful to you as well.)
Here's the thing though. Regardless of what framework you use, or if you go with a console app to test your code, you do have to create a separate project, or a separate, significant chunk of code of some sort, to be able to execute tests properly and independently. That's just part of the process. It is an investment but don't let the extra work keep you from doing it. It will save a lot time, and your skin, a little while in the future. Maybe even next week.
Also, while you're looking up unit testing make sure to also study up on test-driven development (TDD.)
Unit testing is absolutely the way to go. Depending on what version of VS you are running, there may be unit testing functionality built in, or you may have to use an additional tool such as NUnit. Both options are good and will allow you to fully test your classes.
Bear in mind also, that a comprehensive suite of unit tests will make refactoring much easier in the long run as well. If you refactor and break your unit tests, you know you've made a boo-boo somewhere. :)
Unit testing is the way forward here> this is a good introductory article.
The basic concept of a unit test is that you isolate and invoke a specific portion of code and assert that the results are expected and within reason. For example lets say you have a simple method to return the square of a floating point number:
public float Square(float value)
{
return value * value;
}
A reasonable unit test would be that the method returns the correct value, handles negetive values etc:
Assert.AreEqual(25, Square(5));
Assert.AreEqual(100, Square(-10));
Unit tests are also a good way to see how your code handles edge cases:
Assert.Throws<OverflowException>(Square(float.MaxValue));
If you are using VS 2010, check out Pex and Moles...
http://research.microsoft.com/en-us/projects/pex/
The Console App approach is more of a test harness for your class, which is fine.
But you can also use a unit testing framework to test your class. Visual Studio has one built in or you can leverage something like NUnit.
Also, try the Object Test Bench in Visual Studio. It should allow you to create a new instance, modify and view properties, and call some methods. It usually only works with very simple apps, though.
If you use Visual Studio 2008 or higher you will be able to test your code using MSTest framework:
1.Open Test View window: Test/Windows/Test View;
2.Add new unit test project: right click on Solution in Solution Explorer/Add/New
Project/Test Project;
3.Remove all files apart from UnitTest.cs file in created test project;
4.Write your unit test in method under [TestMethod] attribute:
[TestClass]
public class UnitTest1
{
[TestMethod]
public void TestMethod1()
{
var ranges = new Ranges();
int sum = ranges.CountOccurrences(11);
Assert.AreEqual(128, sum);
}
}
5.Run your test from Test View window added in p.1
6.See test results in Test/Windows/Test Results window
I've got a LOT of tests written for a piece of software (which is a GREAT thing) but it was built essentially as a standalone test in C#. While this works well enough, it suffers from a few shortcomings, not the least of which is that it isn't using a standard testing framework and ends up requiring the person running the test to comment out calls to tests that shouldn't be run (when it isn't desired to run the entire test 'suite'). I'd like to incorporate it into my automated testing process.
I saw that the Test Edition of VS 2008 has the notion of a 'Generic Test' that might do what I want, but we're not in a position to spend the money on that version currently. I recently started using the VS 2008 Pro version.
These test methods follow a familiar pattern:
Do some setup for the test.
Execute the test.
Reset for the next test.
Each of them returns a bool (pass/fail) and a string ref to a fail reason, filled in if it fails.
On the bright side, at least the test methods are consistent.
I am sitting here tonight contemplating the approach I might take tomorrow morning to migrate all this test code to a testing framework and, frankly, I'm not all that excited about the idea of poring over 8-9K lines of test code by hand to do the conversion.
Have you had any experience undertaking such a conversion? Do you have any tips? I think I might be stuck slogging through it all doing global search/replaces and hand-changing the tests.
Any thoughts?
If you use NUnit (which you should), you'll need to create a new test method for each of your current test methods. NUnit uses reflection to query the test class for methods marked with the [Test] attribute, which is how it builds its list of the tests that show up in the UI, and the test classes use the NUnit Assert method to indicate whether they've passed or failed.
It seems to me that if your test methods are as consistent as you say, all of those NUnit methods would look something like this:
[Test]
public void MyTest()
{
string msg;
bool result = OldTestClass.MyTest(out msg);
if (!result)
{
Console.WriteLine(msg);
}
Assert.AreEqual(result, true);
}
Once you get that to work, your next step is to write a program that uses reflection to get all of the test method names on your old test class and produces a .cs file that has an NUnit method for each of your original test methods.
Annoying, maybe, but not extremely painful. And you'll only need to do it once.
You're about to live through the idiom of "An Ounce of Prevention is worth a pound of cure". Its especially true in programming.
You make no mention of NUnit(which I think was bought by Microsoft for 2008, but don't hold me to that). Is there a paticular reason you didn't just use NUnit in the first place?