51

Should you Unit Test simple properties of a class, asserting that a value is set and retrieved? Or is that really just unit testing the language?

Example

public string ConnectionString { get; set; }

Test

public void TestConnectionString()
{
    var c = new MyClass();
    c.ConnectionString = "value";

    Assert.Equal(c.ConnectionString, "value");
}

I guess I don't see the value in that.

4
  • 13
    Seems totally pointless to me.
    – Ant P
    Commented Sep 23, 2013 at 19:56
  • 1
    If you were doing something else other than just setting it, I would say yes. But what you're doing is pointless.
    – gleng
    Commented Sep 23, 2013 at 19:57
  • 5
    consider nice and clean article of Mark Seeman Test trivial code Commented Sep 23, 2013 at 19:59
  • To get test coverage, we created a base class to automatically test properties. For more complex properties, we add exceptions and write separate tests.
    – DSway
    Commented Sep 23, 2013 at 20:02

8 Answers 8

63

I would suggest that you absolutely should.

  • What is an auto-property today may end up having a backing field put against it tomorrow, and not by you...

  • The argument that "you're just testing the compiler or the framework" is a bit of a strawman imho; what you're doing when you test an auto-property is, from the perspective of the caller, testing the public "interface" of your class. The caller has no idea if this is an auto property with a framework-generated backing store, or if there is a million lines of complex code in the getter/setter. Therefore the caller is testing the contract implied by the property - that if you put X into the box, you can get X back later on.

  • Therefore it behooves us to include a test since we are testing the behaviour of our own code and not the behaviour of the compiler.

  • A test like this takes maybe a minute to write, so it's not exactly burdensome; and you can easily enough create a T4 template that will auto-generate these tests for you with a bit of reflection. I'm actually working on such a tool at the moment to save our team some drudgery

  • If you're doing pure TDD then it forces you to stop for a moment and consider if having an auto public property is even the best thing to do (hint: it's often not!)

  • Wouldn't you rather have an up-front regression test so that when the FNG does something like this:


//24-SEP-2013::FNG - put backing field for ConnectionString as we're now doing constructor injection of it
public string ConnectionString
{
   {get { return _connectionString; } }
   {set {_connectionString="foo"; } }//FNG: I'll change this later on, I'm in a hurry
}

///snip

public MyDBClass(string connectionString)
{
   ConnectionString=connectionString;
}

You instantly know that they broke something?

If the above seems contrived for a simple string property I have personally seen a situation where an auto-property was refactored by someone who thought they were being oh so clever and wanted to change it from an instance member to a wrapper around a static class member (representing a database connection as it happens, the resons for the change are not important).

Of course that same very clever person completely forgot to tell anyone else that they needed to call a magic function to initialise this static member.

This caused the application to compile and ship to a customer whereupon it promptly failed. Not a huge deal, but it cost several hours of support's time==money.... That muppet was me, by the way!

EDIT: as per various conversations on this thread, I wanted to point out that a test for a read-write property is ridiculously simple:

[TestMethod]
public void PropertyFoo_StoresCorrectly()
{
   var sut = new MyClass();
   sut.Foo = "hello";
   Assert.AreEqual("hello", sut.Foo, "Oops...");
}

edit: And you can even do it in one line as per Mark Seeman's Autofixture

I would submit that if you find you have such a large number of public properties as to make writing 3 lines like the above a chore for each one, then you should be questioning your design; If you rely on another test to indicate a problem with this property then either

  • The test is actually testing this property, or
  • You will spend more time verifying that this other test is failing because the property is incorrect (via debugger, etc) than you would have spent typing in the above code
  • If some other test allows you to instantly tell that the property is at fault, it's not a unit test!

edit (again!): As pointed out in the comments, and rightly so, things like generated DTO models and the like are probably exceptions to the above because they are just dumb old buckets for shifting data somewhere else, plus since a tool created them, it's generally pointless to test them.

/EDIT

Ultimately "It depends" is probably the real answer, with the caveat that the best "default" disposition to be the "always do it" approach, with exceptions to that taken on an informed, case by case basis.

8
  • 4
    Would be really nice if folks downvoting would leave some kind of comment as to why they didn't like the accepted answer... Commented Sep 30, 2013 at 7:18
  • I'm going to do some guess-work here on possible reasons, but the real problem you faced had little to do with unit testing. If you allow such error to get to repo let alone ship to client no amount of tests will help. If such thing happens it's a process problem - lack of (or sloppy) code audits, lack of proper supervision, lack of decent automation, lack of manual testers. Unit tests could have helped, but the core issue lies elsewhere. On top of that, unit tests for autoproperties is a lot of boilerplate code to maintain... which is never good.
    – k.m
    Commented Sep 30, 2013 at 23:06
  • @jimmy_keen - but unit testing is part of the process you allude to; in my case it was a small company with 3 developers and too much work. There were no code audits or manual testers. You can criticise that from an ivory tower if you like (and I'd agree with you on a theoretical level), meanwhile back in the real world we had work to do and bills to pay...so I fail to see how my answer is invalid because it's provably correct that if I had written a unit test the problem would not have slipped out into the wild. And how is a 3 line test method "a lot of boilerplate"? Commented Oct 1, 2013 at 8:02
  • But surely other unit tests that used the property would fail just as loudly as the unit test for the property itself. I still don't see why adding a unit test for the property would have helped. Surely in this situation, every query run with that connection string would blow up instantly. Commented Oct 1, 2013 at 14:20
  • 2
    Model classes are often little more than collections of public properties, and that's not a bad design. If you have a complex domain model, you would end up with literally hundreds of these minor unit tests, which would need to be maintained every time the model is refactored. If the "unit" being tested is the object, then the current state of that object can reasonably be expected to have an effect on the output of the methods. Testing those methods is still a unit test, even if they rely on the state of the object. Commented Oct 1, 2013 at 16:50
44

Generally, no. A unit test should be used to test for the functionality of a unit. You should unit test methods on a class, not individual, automatic properties (unless you are overriding the getter or setter with custom behaviour).

You know that assigning a string value to an automatic string property will work if you get the syntax and setter value correct as that is a part of the language specification. If you do not do this then you will get a runtime error to point out your flaw.

Unit tests should be designed to test for logical errors in code rather than something the compiler would catch anyway.

EDIT: As per my conversation with the author of the accepted answer for this question I would like to add the following.

I can appreciate that TDD purists would say you need to test automatic properties. But, as a business applications developer I need to weigh up, reasonably the amount of time I could spend writing and performing tests for 'trivial' code such as automatic properties compared to how long it would reasonably take to fix an issue that could arise from not testing. In personal experience most bugs that arise from changing trivial code are trivial to fix 99% of the time. For that reason I would say the positives of only unit testing non-language specification functionality outweigh the negatives.

If you work in a fast paced, business environment which uses a TDD approach then part of the workflow for that team should be to only test code that needs testing, basically any custom code. Should someone go into your class and change the behavior of an automatic property, it is their responsibility to set up a unit test for it at that point.

6
  • 3
    +1 also, you test these properties indirectly. E.g. if they aren't covered in other tests then they aren't needed.
    – Finglas
    Commented Sep 29, 2013 at 10:09
  • -1; with all respect and not wanting to turn this into a religious debate but unit tests serve many purposes on top of simply testing methods, not least of which is serving as a regression test point so that you catch breaking changes early on. Granted, having public R/W properties on a class may very well be the real WTF, but if your design calls for it, then you really should be unit testing it...none of us can predict what change might be made by someone else to our code in 6 month's time. Commented Sep 30, 2013 at 15:39
  • 2
    I would argue in the case of a built in language feature (automatic properties in this case) there is no need to unit test it at all as it serves no purpose other than to test a feature you know will work. If you have this property in an environment of developers who all work to TDD practices, then they would know that should they change the behaviour of this property at any point, to add in a unit test then, when it no longer conforms to the language specification.
    – BenM
    Commented Sep 30, 2013 at 18:36
  • @BenM in an ideal world, yes, of course you would expect that when a developer was making a change like that he would also unit test, but as we know in actual fact that doesn't always happen. That's my point - being disciplined about TDD and writing the tests up front (or at least, in the same session as your code) means that we never have to have "help, we should have done that but we didn't and now everything is on fire!". So as I already stated it's not about testing the compiler. It's guarding against your process breaking/lazy programer/me in the future :) Commented Oct 1, 2013 at 8:07
  • I guess then that I take a slightly less strict view of TDD. I'm not what you would call a purist, I use unit testing where I personally can see the benefits. In the future it may well come and bite me in the ass, but then I have to take into consideration the amount of time I would spend testing each automatic property in the first place with the amount of time spent fixing an issue that arises from changing one, which, with great debugging tools included in VS I would not anticipate it taking too long at all. Although I've probably now gone and cursed myself.
    – BenM
    Commented Oct 1, 2013 at 13:06
4

I would have to say no. If that doesn't work, you have bigger problems. I know I don't. Now some will argue that having the code alone would make sure the test failed if the property was removed, for example. But I'd put money on the fact that if the property were removed, the unit test code would get removed in the refactor, so it wouldn't matter.

3
  • I would agree, but I have heard some really push hard for it. I could see a property getter that had some logic in it.
    – Sam
    Commented Sep 23, 2013 at 19:57
  • 4
    @Sam, that may be realistic, but that's not the example that you gave. An automated property, like the one you provided, there's no value in testing it. If it's got a lot of work in it - you might be able to argue that. Commented Sep 23, 2013 at 19:58
  • 1
    @Sam, in that case where it has logic in it, then it could be deemed acceptable to test it, but it would be pointless otherwise. Commented Sep 23, 2013 at 20:00
4

Are you adhering to strict TDD practices or not?

If yes then you absolutely should write tests on public getters and setters, otherwise how will you know if you've implemented them correctly?

If no, you still probably should write the tests. Though the implementation is trivial today, it is not guaranteed to remain so, and without a test covering the functionality of a simple get/set operation, when a future change to implementation breaks an invariant of "setting property Foo with a value Bar results in the getter for property Foo returning value Bar" the unit tests will continue to pass. The test itself is also trivially implemented, yet guards against future change.

2

The way I see is that how much unit testing (or testing in general) is down to how confident are you that the code works as designed and what are the chances of it breaking in the future.

If you have a lower confidence of the code breaking (maybe due to the code being out sourced and the cost of checking line by line is high) then perhaps unit testing properties is appropriate.

Once thing you can do is write a helper class that can go over all get/set properties of a class to test that they still behave as designed.

1
  • Another way to put what you're saying is "How confident do you need to be that the code works".
    – Bryan S.
    Commented Sep 15, 2014 at 20:05
1

Unless the properties perform any other sort of logic, then no.

Yes, it is like unit testing the language. It would be completely pointless to test simple auto-implemented properties otherwise.

1

According to the book The Art of Unit Testing With Examples in .NET, a unit test covers not any type of code, it focuses on logical code. So, what is logical code?

Logical code is any piece of code that has some sort of logic in it, small as it may be. It’s logical code if it has one or more of the following: an IF statement, a loop, switch or case statements, calculations, or any other type of decision-making code.

Does a simple getter/setter wrap an any logic? The answer is:

Properties (getters/setters in Java) are good examples of code that usually doesn’t contain any logic, and so doesn’t require testing. But watch out: once you add any check inside the property, you’ll want to make sure that logic is being tested.

1

My answer which is from former test manager viewpoint and currently a development manager ( responsible for software delivery in time and quality) viewpoint. I see people are mentioning pragmatism. Pragmatism is not a good adviser because it may pair up with laziness and/or time pressure. It may led you on the wrong way. If you mention pragmatism you have to be careful to keep your intentions on the track of professionalism and common sense. It requires humility to accept the answers because they might not that you want to hear.

From my viewpoint what is important are the next:

  • you should find the defect as early as possible. Doing so you have to apply proper testing strategy. If it is testing properties then you have to test properties. If not, then don't do it. Both comes with a price.
  • your testing should be easy and fast. The bigger part (unit, integration, etc.) of the code tested in build time is the better.
  • you should do root cause analysis to answer the questions below and make your organization protected from the current type of error. Don't worry, another type of defect will come up and there will be always lessons to be learned.
    • what the root cause is?
    • how to avoid it next time?
  • another aspect is the cost of creating/maintaining tests. Not testing properties because they are boring to maintain and/or you have hundreds of properties is ridiculous. You should create/apply tools which makes the woodcutting job instead of human. In general, you always have to enhance your environment in order to be more efficient.
  • what other says are not good adviser - doesn't matter whether it was said by Martin Fowler or Seeman - the environment they are I'm pretty sure not the same as you are in. You have to use your knowledge and experience to setup what is good for your project and how to make it better. If you apply things because they were said by people you are respect without even thinking it through you will find yourself in deep trouble. I do not say that you don't need advises and/or other people help or opinion, you have to apply common sense to apply them.
  • TDD does not answer two important question, however, BDD does give you answers for the questions below. But, if you follow only one, you won't have delivery in time and quality. So doesn't matter whether you are purist TDD guy or not.
    • what must be tested? ( it says everything must be tested - wrong answer in my opinion )
    • when testing must be finished?

All in all, there is no good answer. Just other questions you have to answer to get that temporary point where you are able to decide whether it is needed or not.

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.