Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
579 views
in Technique[技术] by (71.8m points)

java - Good patterns for unit testing form beans that have annotation-based validation in Spring MVC

When using annotation based validation for a form bean, what is the best practice for unit-testing those beans in order to ensure that correct validations annotations are specified for each field?

For example, if you have:

public class MyForm {
    @NotNull
    private String name;
}

What is the best way to verify that @NotNull is applied to it?

One obvious way is to create a validator, throw a null at it and expect it to fail. But in my view this is not the best way as you'll be testing the behaviour and implementation of @NotNull using that rather than trusting the framework.

Ideally I would want to use reflection or a utility that gives me the possibility of just asserting that an @NotNull (and any other) validation is applied to a given field, rather than having to send various combination of values that fail validation.

Is there an elegant way of doing this, or am I on the right track in general?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Two things you should consider:

Do Not test your third party libraries/frameworks.

You should rely on them, they are supposed to be already tested by their maintainers and the surrounding community usage. You don't test them, you rather assess them. To make sure that they fit your needs and mitigate the risks.

Testing behavior is what matter, really!

In the vast majority of applications there is little place for real UNIT testing as the business logic is either small are widespread across multiple modules of the application. So you should consider Integration testing with the same priority than Unit testing. And this is more easily captured by using a behavioral approach.

So, to answer your question, you should not try to Unit test a form bean at all. It's just a transport object. What you should test is how the receiver react with that form, and check both the normal case and the edge cases.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...