问题描述:

I am new to Nunit and Moq

I have a static class like this:

public static class StaticClass1

{

public static void Prepare()

{

//some logic

}

}

public static class StaticClass2

{

public static void Initialize(some_parameter)

{

//some logic

if (some_condition(some_parameter))

{

StaticClass1.Prepare();

}

}

}

I need to test the function AccountService.Initialize() in which I need to verify StaticClass1.Prepare() is being called at least once

网友答案:

I think that to answer this question I would say something like "You need to get experience in how to layer a project".

When unit testing a method you want to unit test that single method, and mock the dependencies, exactly as you try to do if I understand you correctly. Now it's not optimal to call static public methods from one class to another static method in another class since it makes it difficult to isolate you unit tests and what they should test (you end up with testing two completely different methods in the same unit test instead of separating the code and unit tests).

On another approach you break the D in SOLID (Dependency inversion principle) that you can read more about here -> https://en.wikipedia.org/wiki/SOLID_(object-oriented_design). You want to depend upon abstractions rather than concrete classes.

Lastly I thought that I would be a bit selfish and share a link to an article series that I have written myself. It's about Test Driven Development and uses Moq as unit testing tool and focuses on how to think when layering and unit testing a complete project (in a small scale). I'm absolute certain that it will help you understand on how to continue with you own projects and code.

It's based upon 4 articles. The first in the series is here -> http://www.andreasjohansson.eu/technical-blog/getting-started-unit-testing-a-web-project-part-1-introduction-and-setting-up-the-project/

Hope it helps!

相关阅读:
Top