testing - Is it possible to mock the "type name" of a mock in C# using Moq? -
i'm developing chatbot in c# (based on .net core) has modular behaviours. 1 of behaviours want develop "admin" module (among other functions) should allow admins dynamically enable or disable other behaviours name.
i want admin module determine name of behaviour inspecting type info , doing like:
var name = behaviour.gettype().gettypeinfo().name.replace("behaviour", string.empty).tolowerinvariant();
in bdd specification i'm writing first, i'm trying set "behaviour chain" consisting of admin module (system under test) , mock behaviour. tests involve sending commands should cause admin module enable or disable mock behaviour.
this i've done far:
public behaviourisenabled() : base("admin requests behaviour enabled") { var mocktypeinfo = new mock<typeinfo>(); mocktypeinfo.setupget(it => it.name).returns("mockbehaviour"); var mocktype = new mock<type>(); mocktype.setup(it => it.gettypeinfo()).returns(mocktypeinfo.object); // todo: make mock behaviour respond "foo" var mockbehaviour = new mock<imofichanbehaviour>(); mockbehaviour.setup(b => b.gettype()).returns(mocktype.object); this.given(s => s.given_mofichan_is_configured_with_behaviour("administration"), addbehaviourtemplate) .given(s => s.given_mofichan_is_configured_with_behaviour(mockbehaviour.object), "given mofichan configured mock behaviour") .and(s => s.given_mofichan_is_running()) .when(s => s.when_i_request_that_a_behaviour_is_enabled("mock")) .and(s => s.when_mofichan_receives_a_message(this.johnsmithuser, "foo")) .then(s => s.then_the_mock_behaviour_should_have_been_triggered()) .teardownwith(s => s.teardown()); }
the problem when run gettypeinfo()
extension method on type
, moq throws exception:
expression references method not belong mocked object: => it.gettypeinfo()
an alternative, add name
property imofichanbehaviour
, don't idea of adding arbitrary methods/properties production code that's there benefit of test code.
keep simple fake class satisfies being mocked.
public class mockbehaviour : imofichanbehaviour { ... }
and test like
public behaviourisenabled() : base("admin requests behaviour enabled") { // todo: make mock behaviour respond "foo" var mockbehaviour = new mockbehaviour(); this.given(s => s.given_mofichan_is_configured_with_behaviour("administration"), addbehaviourtemplate) .given(s => s.given_mofichan_is_configured_with_behaviour(mockbehaviour), "given mofichan configured mock behaviour") .and(s => s.given_mofichan_is_running()) .when(s => s.when_i_request_that_a_behaviour_is_enabled("mock")) .and(s => s.when_mofichan_receives_a_message(this.johnsmithuser, "foo")) .then(s => s.then_the_mock_behaviour_should_have_been_triggered()) .teardownwith(s => s.teardown()); }
Comments
Post a Comment