When unit testing using expectations, you define a set of method calls and corresponding results for those calls. These define the path through the method that you want to test.

I have read that unit tests should not duplicate the code. But when you define these expectations, isn't that duplicating the code, or at least the process? How do you know when you're duplicating functionality under test?

2 Answers 2


Expectations should be different but if you're testing with a common set of expectations across several unit tests you should use variables and objects that are shared.

This is also why you have the setUp and tearDown methods for in xUnit frameworks.

Some frameworks take this one step further letting you set up with nesting such as Jasmine (BDD/TDD for Javascript).

  • Funny - there's also a Jasmin (no trailing 'e') that is a Java assembler!
    – Michael K
    Commented Feb 3, 2011 at 20:02

It depends on how trivial the methods are that you are testing.

Example A -- trivial code, trivial test(s)

public class SomeClass
  public string SomeStringProperty { get; set; }
  public SomeClass(string someString)
      SomeStringProperty = someString;

public void SomeClassConstructorSetsSomeStringProperty()
  string testString = "abc";
  SomeClass some = new SomeClass(testString);
  Assert.AreEqual(testString, some.SomeStringProperty);

Save methods, property getters, setters and simple constructors all fall into this category. The setup methods and assertions will be simple and resemble the code under test to the point where you would think that they are duplicative. Many articles about how to do unit testing have trivial examples like this, and then people think unit testing doesn't look that valuable. I don't blame them for thinking that if those are the only examples that they've seen.

Example B -- more complex code, more tests required.

public class PaymentCalculator
  public int DayOfMonth { get; set; }
  public int IsRecipientLikable { get; set; }

  public decimal PaymentAmount()
    decimal payment = 0;
    if (DayOfMonth < 15) payment += 100;
    if (IsRecipientLikable) payment *= 6;
    return payment;

public void PaymentOn4thForLikeablePersonIs600Dollars()
  var calc = new PaymentCalculator { DayOfMonth = 4, IsRecipientLikable = true };
  Assert.AreEqual(600, calc.PaymentAmount());

Obviously, this one test won't cover all the conditions of your "calculator", so you would need to write several more.

In summary, the more complex your business logic is, the more meaningful, and less-duplicative your tests can and should be.

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.