Featured post
c# - Unit testing with Mocks. Test behaviour not implementation -
i had problem when unit testing classes calls other classes, example have class creates new user phone-number saves database , sends sms number provided.
like code provided below.
public class userregistrationprocess : iuserregistration { private readonly irepository _repository; private readonly ismsservice _smsservice; public userregistrationprocess(irepository repository, ismsservice smsservice) { _repository = repository; _smsservice = smsservice; } public void register(string phone) { var user = new user(phone); _repository.save(user); _smsservice.send(phone, "welcome", "message!"); } }
it simple class how go , test it?
at moment im using mocks dont it
[test] public void whenregistreringanewuser_thenewuserissavedtothedatabase() { var repository = new mock<irepository>(); var smsservice = new mock<ismsservice>(); var userregistration = new userregistrationprocess(repository.object, smsservice.object); var phone = "07012345678"; userregistration.register(phone); repository.verify(x => x.save(it.is<user>(user => user.phone == phone)), times.once()); } [test] public void whenregistreringanewuser_itwillsendanewsms() { var repository = new mock<irepository>(); var smsservice = new mock<ismsservice>(); var userregistration = new userregistrationprocess(repository.object, smsservice.object); var phone = "07012345678"; userregistration.register(phone); smsservice.verify(x => x.send(phone, it.isany<string>(), it.isany<string>()), times.once()); }
it feels testing wrong thing here?
any thoughts on how make better?
refactoring mocks out in way @serghei suggests good.
i see name of behaviour isn't describing behaviour. use word "should", in, "my class should stuff
".
your class shouldn't send user database when it's registering user. should ask repository save user. that's all. doesn't know whether repository sends database, keeps in memory or nukes orbit. it's not class's responsibility.
by phrasing behaviour way, can explicitly show - , others understand - scope of class's responsibility ends.
if rename method whenregisteringanewuser_asksrepositorytosaveit()
might make example you've given feel more natural.
- Get link
- X
- Other Apps
Comments
Post a Comment