mocking - How to mock a validator for unit testing -



mocking - How to mock a validator for unit testing -

i have method validate object calling external service:

public void validate(ivalidator<mytype> validator) { imapper<mytype> mapper = new mytypemapper(); foreach (var element in this.elements) { validationresult result = validator.validate(mytypeinstance, mapper, new validationconfiguration()); if (result.isvalid) // else // else } }

now in unit test have collection of elements. , want if element have given id number validate method should homecoming stub validation messages:

// arrange var myaggregate aggregate = elementsnonvalidated.stub(); var mockedvalidator = new mock<ivalidator<mytype>>(); mockedvalidator.setup(a => a.validate( it.is<mytype>(x => x.id == guid.parse("3f2504e0-4f89-11d3-9a0c-0305e82c3301")), new mapper(), new validationconfiguration() )).returns<validationresult>(x => x = new validationresult()); // deed myaggregate.valida(mockedvalidator.object);

the problem is: when unit test starts , go forth till real method validate still homecoming result=null. why? what's wrong mock?

the problem here:

mockedvalidator.setup(a => a.validate( it.is<mytype>(x => x.id == guid.parse("3f2504e0-4f89-11d3-9a0c-0305e82c3301")), new mapper(), new validationconfiguration() )).returns<validationresult>(x => x = new validationresult());

you setup validate expect specific mapper , validationresult instances, of course of study not match instances used in scheme under test. if don't care instance should used parameter, utilize it.isany<>:

mockedvalidator.setup(a => a.validate( it.is<mytype>(x => x.id == guid.parse("3f2504e0-4f89-11d3-9a0c-0305e82c3301")), it.isany<mapper>(), it.isany<validationconfiguration>() )).returns<validationresult>(x => x = new validationresult());

this homecoming new validationresult , every invocation validate object's id equal particular guid.

the reason targetparametercountexception in returns statement, , answered here.

unit-testing mocking moq

Comments

Popular posts from this blog

Delphi change the assembly code of a running process -

json - Hibernate and Jackson (java.lang.IllegalStateException: Cannot call sendError() after the response has been committed) -

C++ 11 "class" keyword -