c# - Unit testing DAL that requires authenticated user -
essentially, trying test action if particular user signed in , doing it. have interface implement on entities required auditing such
public interface iauditableentity { datetime createddate { get; set; } string createdbyid{ get; set; } datetime updateddate { get; set; } string updatedbyid { get; set; } }
in mvc project, i've overwritten savechanges()
function in order automatically fill in fields above:
public override int savechanges() { var modifiedentries = changetracker.entries() .where(x => x.entity iauditableentity && (x.state == system.data.entity.entitystate.added || x.state == system.data.entity.entitystate.modified)); foreach (var entry in modifiedentries) { iauditableentity entity = entry.entity iauditableentity; if (entity != null) { var identityname = (thread.currentprincipal claimsprincipal).findfirst(claimtypes.nameidentifier).value; datetime = datetime.utcnow; if (entry.state == system.data.entity.entitystate.added) { entity.createdbyid = identityname; entity.createddate = now; } else { base.entry(entity).property(x => x.createdbyid).ismodified = false; base.entry(entity).property(x => x.createddate).ismodified = false; } entity.updatedbyid = identityname; entity.updateddate = now; } } return base.savechanges(); }
this works in cases, required sign application before iauditableentity
entity modified. however, unable figure out how unit test this.
it seems reasonable think should call sign in method , things should work there. sign in method essentially:
var ctx = this.request.getowincontext(); ctx.signin(...)
unfortunately, within test project, there no request object. how simulate request
within scope of unit test?
simply set value of thread.currentprincipal
instance of claimsprincipal
inside unit test.
you don't need setup fake httprequest
, using thread.currentprincipal
directly.
Comments
Post a Comment