I want to learn how to write test cases before writing the code. I read an article about test-driven development. I wonder how developers write test cases? For Example this method:
public int divideNumbers(int num1, int num2)
{
return num1 / num2;
}
We start with a blank project now. You want to do something, say divide two numbers. So you write a test describing what you want to do:
Assert.That(divide(10,2), Eq(5))
This test gives you an entry point: it describes the acceptable interface of the divide
method. So you proceed to implement it as int divide(int x, int y)
for example.
Write tests that describe what you expect to get from your code. You don't need to think much about it. The most normal way of writing your expectation is probably the best way to design your code, and then you can implement it to satisfy your test.
There are a few steps for testing. From MSDN
;
In your case;
Assert.AreEqual(divideNumbers(8, 4), 2);
Assert
class verifies conditions in unit tests using true
/false
propositions. You should write your test cases what you expecting their results. You can use TestMethod
attribute for your test methods. There is a cool post about Creating Unit tests for your c# code. Analyze it very well.
Start with a stub of the function/class/component that you want to develop. It should compile, but deliberately not (yet) do what it is supposed to do.
For example:
public int divideNumbers(int num1, int num2)
{
throw new NotImplementedException();
}
or
return -42;
Think about the intended behavior, treating the stub as an interface to a black box. Don't care about the implementation (yet). Think about the "contract" of the interface: X goes in, Y goes out.
Identify standard cases and important egde cases. Write tests for them.
For integer division (assuming we would write it from scratch) there are actually quite a couple of cases to consider: With and without remainder, n/1, n/0, 0/n, 0/0, negative numbers, etc.
Assert.IsTrue(divideNumbers(4,4) == 1);
Assert.IsTrue(divideNumbers(4,3) == 1);
Assert.IsTrue(divideNumbers(4,2) == 2);
Assert.IsTrue(divideNumbers(4,1) == 4);
Assert.Throws<ArgumentException>(() => divideNumbers(4,0));
Assert.IsTrue(divideNumbers(0,4) == 0);
Assert.Throws<ArgumentException>(() => divideNumbers(0,0));
Assert.IsTrue(divideNumbers( 4,-2) == -2);
Assert.IsTrue(divideNumbers(-4, 2) == -2);
Assert.IsTrue(divideNumbers(-4,-2) == 2);
Assert.IsTrue(divideNumbers( 4,-3) == -1);
Assert.IsTrue(divideNumbers(-4, 3) == -1);
Assert.IsTrue(divideNumbers(-4,-3) == 1);
Compile and run the unit tests. Do they all fail? If not, why? Maybe one of the tests is not working as intended (tests can be buggy, too!).
Now, start to implement until no test fails anymore.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With