Given the the following method what and how can I test?
public void DoSomething
{
Get Db record
Update Db the record
Log History in Db
Send an email notification
}
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
First of all, I agree with the other posters that this method is doing too much. I personally would have it do only the Db stuff, then have my application layer log the action and send the email. That said, to unit test this method, I would do the following (in C#):
Firstly, give the class that method exists in a constructor like this:
…where the
IRepositoryis an interface something like this:…the
ILoggingServiceis something like this:…and the
INotificationClientis something like this:In the constructor body, assign the passed-in parameters to private, readonly fields in
MyClass.Next, in the
DoSomethingmethod, get theDbrecord from theIRepository, update it and save it back to theIRepository. Log the history using theILoggingService, then callSendNotification()on theINotificationClient.Finally, in your unit tests, use a mocking framework (like Moq) to mock up one of each of the interfaces. Pass the mocked objects into a new instance of
MyClass, callDoSomething(), then verify that your mockedIRepositoryhas been asked to update theDbobject, your mockedILoggingServicehas been asked to log a message, and your mockedINotificationClienthas been asked toSendNotification(). That is to say:In the running system you would inject proper implementations of
MyClass‘ dependencies, and you’ve then shared the responsibilities amongst more coherent objects.Bit long-winded, but that’s how I’d do it 🙂