To unit test the method doSomethi开发者_Go百科ng(String name) in ClassA below, what things should I test on the return value?
My first thought is to test
- that the name attribute is set properly on Wrapper
- that the formattedName attribute on Wrapper is properly formatted
But on second thought, should I instead test the value of formattedName in the unit test for UtilClass.format(String name)? Or should I do it in both places?
public class ClassA {
public Wrapper doSomething(String name) {
Wrapper wrapper = new Wrapper();
wrapper.setName(name);
wrapper.setFormattedName(UtilClass.format(name));
return wrapper;
}
}
The test-first approach is interesting, it says do not write a line of code until you have a failing test--then only write enough code to make your test pass.
Were you to follow this plan, you would actually end up with some pretty thorough tests.
I would have tests that validate that name and formatted name have the appropriate values. To decouple the method from UtilClass
I'd use injection and also validate, using mocks, that the UtilClass.format
method is called. Your test for the formatted name, then would check that the value is equal to the result returned from your mock. I'd also have (probably the first test to write) a test that verifies that you get a non-null result when you call the method. Test UtilClass
methods separately.
EDIT: I'd agree with @Bill K that you should definitely write the tests first.
As UtilClass
has a format
method you should test it at part of that class's unit tests.
You're tests of the Wrapper
class should be to make sure that it doesn't modify the data in any way, assuming that's its purpose of course. If it's purpose it to modify the data then you should test that.
I like to do black-box unit testing. So, in this case, I'll test whatever the "do something" means on the return. If it means that it the name should be set and formatted, then I'll test that.
I'll also test with null and empty string as base cases.
Since you know the internals of the method you are testing when writing a unit test, you have what you need there in the method itself:
test arguments (what happens if name is a null string? or a very long string?)
test return values/objects (test to make sure this method isn't returning a null reference)
test the data being modified within the method (call getName and verify it was set correctly, call getFormattedName to verify this data also).
These are just some initial ideas to get you started on things you should be testing.
To answer your second question, my opinion is that you should test the getFormattedName method within the unit test of Wrapper itself. That way, if the Wrapper class or getFormattedName method changes in the future and the unit test needs to be updated, you only need to track it in one place (in the Wrapper unit test).
精彩评论