0

Let's say I have a model like:

public class Person
{
    [JsonProperty("firstName")]
    public string FirstName{ get; set; }
}

Is there a way to test that class Person has a property called FirstName whose corresponding json property name is firstName?

havij
  • 1,030
  • 14
  • 29
  • Does this answer your question? [Custom attribute on property - Getting type and value of attributed property](https://stackoverflow.com/questions/3289198/custom-attribute-on-property-getting-type-and-value-of-attributed-property) – Pavel Anikhouski Mar 14 '20 at 14:14

1 Answers1

0

Well, you could do that with reflection, the link that @Pavel Anikhouski gave you might help you, but I consider using reflection is always a hacky thing. Sometimes you can't avoid it sure, but you should avoid it if you can.

On the other hand unit testing is not for testing the design of your code/application (that you want to achieve now), rather the testing of it's functionality.

"Check that your code is working as expected by creating and running unit tests. It's called unit testing because you break down the functionality of your program into discrete testable behaviors that you can test as individual units." https://learn.microsoft.com/en-us/visualstudio/test/unit-test-basics?view=vs-2019

Having a property or attribute in a class is not functionality nor behaviour.

To be honest, I don't see any use cases where and when you want to achieve something like this. If you want to test that a class has a property why write lines of code to just check that one specific property? Just open the class code and see if it has that property or not, if it doesn't have it then write it in the code.

zsolt
  • 1,233
  • 8
  • 18
  • "To be honest, I don't see any use cases where and when you want to achieve something like this", is functionality only defined by functions? To me, the functionality of this class depends on the JSON property name of its properties. – havij Mar 15 '20 at 12:02
  • Yes, I would say. A class by itself can not function, you need to instantiate it and call its member method (or if it's static call its static method) and test them. Or if your class doesn't have any method then you should test the method of the consumer of your class/object. – zsolt Mar 15 '20 at 12:14