unit testing - How do I create a mock instance inside of a method in C#? -


So here is the simplified version of my classes. I have two classes that apply a service interface. I am a real implementation of my And my motive is.
I need to create a number of new examples of this service class inside my worker class.

How do I tell my working class who want to use IISIS I?
Does the only way to go to the working class enjoy? Is there any better way?

Edit: Then after reading some reactions, I think I did not tell my position correctly. I was overwritten on the issue of obstruction anyway I have added more code which can help to clarify what I am doing

I have used the original worker class < Code> manager and has a child list of workers . The list of workers is created from the manager class and I create them by using IService , which I want to concrete or imitated the implementation, then I get the workers To do something related to IService and remove a variable that I provide it to. (In this case it is just an integer, but in real life it is a class). Public Interface IService {int a {get; Set; }} Public Sector Concrete: IService {public int a {get; Set; } Float x; Public Concrete (int A) {a = A; X = 0.500 F; }} Public class mock: IService {public int one {get; Set; } Float x; Public mock (int a) {a = A; X = 0.750f; }} Public Class Manager {List & lt; Worker & gt; Worker = new list & lt; Worker & gt; (); Zero CreateList () {for (int i = 1; i & lt; = 3; i ++) {worker w = new worker (new IS ervice (i)); // & lt; - Need help here! (W) theList.Add; } KickoffWorks Async (); } Zero-kickoffworks async () {// workers async}} public class workers {iSys _iService; Public worker (IService _iSer) {_iService = _iSer; } Void DoSomething () {// work with _iService}}

one The alternative is to provide a factory method to the worker who will make the service:

  Public class employees {Private Func & lt; int, IService & gt; createService; Public Worker (Funk & lt; int, IService & gt; createService) {this.createService = createService; }   

Then the worker can do this:

  zero doSomething () {var theList = new list & lt; IService & gt; (); For (int i = 1; i   

and the unit test can create similar workers:

  Public Zero Certain TestMethod () {Var Worker = new employee (CreateMockService); } Private IService CreateMockService (int arg) {new simulated return (arg); }   

The production code will provide a factory method to create genuine services.

Comments

Popular posts from this blog

Verilog Error: output or inout port "Q" must be connected to a structural net expression -

jasper reports - How to center align barcode using jasperreports and barcode4j -

c# - ASP.NET MVC - Attaching an entity of type 'MODELNAME' failed because another entity of the same type already has the same primary key value -