Unit test using dependency injection and mock objects without hitting Database -
i'm new unit testing.can explain me how done unit testing without hitting database.
and want know that, is dependency injection essential unit testing? if yes, explain me sample code. helpful me.
i had created unit testing login, hits database. want test same case login, without hitting database. in this, used microsoft.visualstudio.testtools.unittesting.
here code,
[testmethod] public void _01_loginuser_01_valid() { bluser.user.userdto user = new bluser.user.userdto(); user.username = "mohan"; user.userpassword = "abc"; bluser.model.fs_user result = bluser.user.loginuser(user); assert.areequal("mohan", result.username); }
and business logic is,
public static fs_user loginuser(userdto userdto) { try { var context = new userdbentities(); { var loginuser = context.fs_user.where(u => u.username == userdto.username && u.userpassword == userdto.userpassword).singleordefault(); if (loginuser == null) validationerror.loginexception((int)exceptioncodes.invalidpassword); return loginuser; } } catch (exception ex) { throw ex; } }
see answer here: solid principle examples anywhere?
if @ idea of depending on interface data access, you'll see how supply 'fake' implementation of interface testing not depend on database.
based on example, need make following changes:
public class loginthing { private readonly iamsomecontext context; public loginthing(iamsomecontext context) { this.context = context; } public fs_user loginuser(userdto userdto) { try { var loginuser = this.context.fs_user .singleordefault( u => u.username == userdto.username && u.userpassword == userdto.userpassword); if (loginuser == null) validationerror.loginexception((int)exceptioncodes.invalidpassword); return loginuser; } catch (exception ex) { throw ex; } } }
and test can become like:
[testmethod] public void _01_loginuser_01_valid() { bluser.user.userdto user = new bluser.user.userdto(); user.username = "mohan"; user.userpassword = "abc"; var fakecontext = createfakecontextwith(user); var thingundertest = new loginthing(fakecontext); bluser.model.fs_user result = thingundertest.loginuser(user); assert.areequal("mohan", result.username); }
creating fake context this, if used nsubstitute:
private iamsomecontext createfakecontextwith(bluser.user.userdto user) { var fakecontext = substitute.for<ifakecontext>(); fakecontext.fs_user.returns(new list(new[] {user})); return fakecontext; }
the syntax might not exact, point...
Comments
Post a Comment