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,

  • You're trying to test built in operators?
    – user40980
    Aug 1, 2014 at 17:30
  • I'm trying to test a logic gate, could be or exor etc, it is for learning how to solve a problem with a test? Aug 1, 2014 at 17:31
  • ... you're trying to test a built in such as &&, ^, ||?
    – user40980
    Aug 1, 2014 at 17:32
  • I'm trying to test a processing machine, input is 2 operators in this case yes, and process is and/or/exor output is ... the output of the logic operation, i just want to understand how to go from test Aug 1, 2014 at 17:33

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:

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. 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);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.