I'm learning about unit tests, and have a doubt for a test i want to do,
to implement an "AND" logic gate
A B A^B
0 0 0
0 1 0
1 0 0
1 1 1
how can i test for a method that works like AND gate?, is this what a mock object is? or stub? Thanks,
Please provide pseudo code,
2 Answers 2
I assume you're just looking for an example of how to write a unit test for something like an AND gate.
Depending on your unit test framework, you can use parameterized unit tests, like in NUnit:
[RowTest]
[Row(0,0,0)]
[Row(0,1,0)]
[Row(1,0,0)]
[Row(1,1,1)]
public void TestAndGate(int a, int b, int expected)
{
var test = new AndGateImplementation();
Assert.AreEqual(expected, test.And(a,b));
}
-
A nitpicking note: although there are only four possible input combinations, this still doesn't expose all possible errors. A very badly written implementation might inadvertently be stateful, so that the second call to
AndGateImplementation(1,0)
returns something different form the first one! You could repeat tests to try to detect such catastrophic errors, but it might not be worth the extra effort. Also, you could test input values other than 0 and 1; if the contract specifies a particular behavior for out-of-band input, then not fulfilling it would be a defect, so it has to be tested.Kilian Foth– Kilian Foth2014年08月01日 19:41:32 +00:00Commented Aug 1, 2014 at 19:41
Unit tests verify that a function returns properly for a handful of inputs and known outputs. In the case of a simple logic function, you actually have the advantage of testing every input/output:
// this is what you're testing:
public Boolean And(Boolean p1, Boolean p2);
// depending on your testing framework, your test might look like this
public void TestAnd() {
TestAnd(true, true, true);
TestAnd(true, false, false);
TestAnd(false, true, false);
TestAnd(false, false, false);
}
public void TestAnd(Boolean p1, Boolean p2, Boolean r) {
Assert.Equal(And(p1, p2), r);
}
&&
,^
,||
?