Need some information in VS unit Test Assert.Inconclusive? - c#

I am working on some unittest projects in VS 2008 in C#, i created one simple small method for unit test?
public int addNumber(int a, int b)
{
return a + b;
}
well i created a unit test method as below,
[TestMethod()]
public void addNumberTest()
{
Mathematical target = new Mathematical(); // TODO: Initialize to an appropriate value
int a = 4; // TODO: Initialize to an appropriate value
int b = 2; // TODO: Initialize to an appropriate value
int expected = 0; // TODO: Initialize to an appropriate value
int actual;
actual = target.addNumber(a, b);
Assert.AreEqual(expected, actual);
Assert.Inconclusive("Verify the correctness of this test method.");
}
But when i try to run the unittest project ,
I am receiving an Inconclusive message. My question is
what exactly the Inconclusive is and when it comes into the picture?
what are the necessary things, i need to do to make my unit test passed?

You need to decide what the criteria is for a unit test to be considered passed. There isn't a blanket answer to what makes a unit test pass. The specifications ultimately dictate what constitutes a passing unit test.
If the method you are testing is indeed just adding two numbers, than the Assert.AreEqual(expected,actual) is probably enough for this particular unit test. You may also want to check Assert.IsTrue(expected>0) That may be another assertion you could tack on to this unit test.
You'll want to test it again though with other values like negatives, zeros, and really large numbers.
You won't need the Inconclusive operator for your unit tests of the addNumber method. That assertion would be more useful when dealing with objects and threads possibly. Calling the Inconclusive assertion like you have will always fail and always return the string passed into it.

Related

Using NUnit Multiple Assert when Assert statements are in different methods

I am running automated BDD steps using NUnit assertions for each step i.e. Then And for my UI tests.
The NUnit assertions are confined to confined to each method. This means that if an assertion in a method fails, then the other steps won't be run.
I was thinking of using NUnit Multiple Assert but this requires all the asserts to be together. Any ideas?
BDD Steps
Then I am shown results for("foo")
And the page count is(3)
I am using the LightBDD Library https://github.com/LightBDD/LightBDD
// Then Step
private void ThenIAmShownResultsFor(string expectedResults)
{
Assert.AreEqual(expectedResults, actual);
}
// And Step
private void AndThePageCountIs(int expectedResults)
{
Assert.AreEqual(expectedResults, actual);
}
See this article. Your tests that are reliant on the result of another should mock those other tests or methods. Each test should be completely decoupled from any other tests. You should never, ever, ever make one test dependent on the results of another. If a test relies on the results of another, you need to mock the response from the other test.
The code, assuming _foo
// And Step
private void AndThePageCountIs(int expectedResults)
{
actual = _foo.Setup(x => x.ThenIAmShownResultsFor()).Returns(expectedResults);
Assert.AreEqual(expectedResults, actual);
}

How to use variables between unit tests? c# webdriver

Im begginer in webdriver and c#. I want to use variable, from first test in another tests, how do I do that? I got to this point with some examples, but it does not work. I see that first test gets the login right, but when I start the second test and try to sendkeys, I get that loginName is null. (code is in short version, only to give you an idea of what Im trying to do)
[TestFixture]
public class TestClass
{
private IWebDriver driver;
private StringBuilder verificationErrors;
private string baseURL;
private bool acceptNextAlert = true;
static public String loginName;
static public String loginPassword;
[SetUp]
public void SetupTest()...
[TearDown]
public void TeardownTest()...
[Test]
public void GetLoginAndPassword()
{
loginName = driver.FindElement(By.XPath("...")).Text;
loginPassword = driver.FindElement(By.XPath("...")).Text;
Console.WriteLine(loginName);
}
[Test]
public void Test1()
{
driver.FindElement(By.Id("UserNameOrEmail")).SendKeys(loginName);
driver.FindElement(By.Id("Password")).SendKeys(loginPassword);
}
You cannot (and should not) send variables between tests. Tests methods are independent from another... and should actually Assert() something.
Your first method GetLoginAndPassword() isn't a test method per se but a utility method. If you use a Selenium PageObject pattern, this is probably a method of your PageObject class that you can run at the begining of your actual Test1() method.
The problem is that the methods marked with TestAttribute do not run sequentially in the same order you implemented them. Thus it might be possible that Test1 runs long before GetLoginAndPassword). You have to either call that method once from within the constructor or during test-initialization, or before every test-run.
[Test]
public void Test1()
{
GetLoginAndPassword();
driver.FindElement(By.Id("UserNameOrEmail")).SendKeys(loginName);
driver.FindElement(By.Id("Password")).SendKeys(loginPassword);
}
Probably your GetLoginAndPassword isnĀ“t even a method to test but a method used from your tests (unless you actually have a method within your system under test called GetLoginAndPassword. However since there are no asserts at all your tests are somewhat weird.
The purpose of unit testing is to test if a specific unit (meaning a group of closely related classes) works as specified. It is not meant to test if your complete elaborate program works as specified.
Test driven design has the advantage that you are more aware what each function should do. Each function is supposes to transform a pre-condition into a specified post-condition, regardless of what you did before or after calling the function.
If your tests assume that other tests are run before your test is run, then you won't test the use case that the other functions are not called, or only some of these other required functions are called.
This leads to the conclusion that each test method should be able to be run independently. Each test should set up the precondition, call the function and check if the postcondition is met.
But what if my function A only works correctly if other function B is called?
In that case the specification of A ought to describe what happens if B was called before A was called, as well as what would happen if A was called without calling B first.
If your unit test would first test B and then A with the prerequisite that B was called, you would not test whether A would react according to specification without calling B.
Example.
Suppose we have a divider class, that will divide any number by a given denominator that can be set using a property.
public class Divider
{
public double Denominator {get; set;}
public double Divide(double numerator)
{
return numerator / this.Denominator;
}
}
It is obvious that in normal usage one ought to set property Denominator before calling Divide:
Divider divider = new divider(){Denominator = 3.14};
Console.WriteLine(divider.Divide(10);
Your specification ought to describe what happens if Divide is called without setting Denominator to a non-zero value. This description would be like:
If method Divide is called with a parameter value X and the value of Denominator is a non-zero Y, then the return value is X/Y. If the value of Denominator is zero, then the System.DivideByZeroException is thrown.
You should create at least two tests. One for the use case that Denominator was set at a proper non-zero value, and one for the use case that the Denominator is not set at all. And if you are very thorough: a test for the use case that the Denominator is first set to a non-zero value and then to a zero value.

How to programmatically tell NUnit to repeat a test?

How to programmatically tell NUnit to repeat a test?
Background:
I'm running NUnit from within my C# code, using a SimpleNameFilter and a RemoteTestRunner. My application reads a csv file, TestList.csv, that specifies what tests to run. Up to that point everything works ok.
Problem:
The problem is when I put the same test name two times in my TestList file. In that case, my application correctly reads and loads the SimpleNameFilter with two instances of the test name. This filter is then passed to the RemoteTestRunner. Then, Nunit executes the test only once. It seems that when Nunit sees the second instance of a test it already ran, it ignores it.
How can I override such behavior? I'd like to have NUnit run the same test name two times or more as specified in my TestList.csv file.
Thank you,
Joe
http://www.nunit.org/index.php?p=testCase&r=2.5
TestCaseAttribute serves the dual purpose of marking a method with
parameters as a test method and providing inline data to be used when
invoking that method. Here is an example of a test being run three
times, with three different sets of data:
[TestCase(12,3, Result=4)]
[TestCase(12,2, Result=6)]
[TestCase(12,4, Result=3)]
public int DivideTest(int n, int d)
{
return( n / d );
}
Running an identical test twice should have the same result. An individual test can either pass or it can fail. If you have tests that work sometimes and fail another then it feels like the wrong thing is happening. Which is why NUnit doesn't support this out of the box. I imagine it would also cause problems in the reporting of the results of the test run, does it say that test X worked, or failed if both happened?
The closest thing you're going to get in Nunit is something like the TestCaseSource attribute (which you already seem to know about). You can use TestCaseSource to specify a method, which can in turn, read from a file. So, you could for example have a file "cases.txt" which looks like this:
Test1,1,2,3
Test2,wibble,wobble,wet
Test1,2,3,4
And then use this from your tests like so:
[Test]
[TestCaseSource("Test1Source")]
public void Test1(string a, string b, string c) {
}
[Test]
[TestCaseSource("Test2Source")]
public void Test2(string a, string b, string c) {
}
public IEnumerable Test1Source() {
return GetCases("Test1");
}
public IEnumerable Test2Source() {
return GetCases("Test2");
}
public IEnumerable GetCases(string testName) {
var cases = new List<IEnumerable>();
var lines = File.ReadAllLines(#"cases.txt").Where(x => x.StartsWith(testName));
foreach (var line in lines) {
var args = line.Split(',');
var currentcase = new List<object>();
for (var i = 1; i < args.Count(); i++) {
currentcase.Add(args[i]);
}
cases.Add(currentcase.ToArray());
}
return cases;
}
This is obviously a very basic example, that results in Test1 being called twice and Test2 being called once, with the arguments from the text file. However, this is again only going to work if the arguments passed to the test are different, since nunit uses the arguments to create a unique test name, although you could work around this by having the test source generate a unique number for each method call and passing it to the test as an extra argument that the test simply ignores.
An alternative would be for you to run the nunit from a script that calls nunit over and over again for each line of the file, although I imagine this may cause you other issues when you're consolidating the reporting from the multiple runs.

Does this negative unit testing make sense

I have tests like that. Negative unit testing.
Does this test make sense? Is it not better to test only the expected exceptional scenarios?
[Test]
public void Get_Root_Units_By_Non_Existing_TemplateId()
{
// ARRANGE
ITemplateUnitDataProvider provider = new TemplateUnitDataProvider(_connectionString);
int templateId = -1;
// ACT
var units = provider.GetRootUnits(templateId);
// ASSERT
Assert.IsNotNull(units);
Assert.Count(0, units);
}
For me this test makes sense. You are checking that the SUT (Subject Under Test) returns an empty array if it hasn't found any records matching the input parameter.
In my opinion, unit tests are used to check your method's correctness. Handling incorrect input correctly is also something you want to test for.
Unit tests are meant to give you a sense of security about your code, so handling invalid input is certainly something I would test.
One good reason to wite fail test is any unit test is better than no unit test
writing fail test lets you know your system well what it should fail on else you have some other scenario's that you are not aware of

How to check if a private method was called with expected argument in unit test?

I am writing unit for a class which looks like following using nunit and Rhino mock.
Class MyClass
{
private void M()
{
N("Hi");
}
private void N(string text)
{
........ do something
}
}
For the unit test for method M I want to check if method N was called with argument "Hi". How do I do it?
It seems to me that from the point of view of testing, you're delving into the implementation details of your object. Can't you perform your tests by checking the ultimate result of your method call ? That is, presumably these method calls have some effect. So rather than checking the arguments being passed, you should be checking the final result.
That way you can change your underlying code at a later date, and your unit tests will confirm that the ultimate result is the same, independent of your implementation.
+1 to Brian's response.
The alternative is to split "N" out to a different class, and then use a mocked instance of that class in your test. You can then set up the mock to expect a call with a specific parameter. But, it might not actually be appropriate to split it out. Depends on your exact scenario.
Use mocking on your method N().
http://www.mockobjects.com/
However, Brian solution is better -- think it's a good direction for good unit testing.
Following code can help you.
var mock = new Mock<IFoo>();
bool called=false;
string test=string.empty;
mock.Setup(foo => foo.Execute(It.IsAny<string>())).Callback((string s) => { test = s; called = true;});
Assert.IsTrue(called, "Execute() was not called");

Categories