Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any good way to switch different context between Unit Test and Release. in C#

I have some context in code to be switched depending on whether it is running under test or release. Say in my product coding:

PublishRequest(); // the real one
//PublishRequestPsudo(); // the one want to be run during unit test

The way I am thinking about is make a TestFlag class:

if (!TestFlag.PublishFlag)
{
    PublishRequest();
}
else
{
    PublishRequestPsudo();
}

This seems verbose if I have many place to do that. Is there any good pattern to do it?

like image 645
demaxSH Avatar asked May 30 '11 07:05

demaxSH


People also ask

What is the recommended way to separate the code that you are testing from its related dependencies?

Mocking is a process used in unit testing when the unit being tested has external dependencies. The purpose of mocking is to isolate and focus on the code being tested and not on the behavior or state of external dependencies.

Which of the following is the best approach to decouple test inputs from test implementation?

Using Preconditions to Avoid Coupling A precondition hides all the implementation details we need to mock out from the test.

What are best practices for unit testing methods that use cache heavily?

If you want true Unit Tests, then you have to mock the cache: write a mock object that implements the same interface as the cache, but instead of being a cache, it keeps track of the calls it receives, and always returns what the real cache should be returning according to the test case.

Should unit tests be in the same package?

The need to test protected interfaces means that unit tests should belong to the same package as the production classes they test, so they must have the same directory path. This can be done by creating separate but parallel hierarchies for the production and test code.


1 Answers

A pretty good way to acheive the same is Dependency Injection/Inversion Of Control

Another good resource on this is Caching ArchitectureTestability, Dependency Injection and Multiple Providers

like image 147
Furqan Hameedi Avatar answered Sep 29 '22 12:09

Furqan Hameedi