Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

220
Views
Unit Testing a method which contains a Using block

I have a already written (was written years ago) C# function, I have been asked to cover this method with Unit Tests.

public string PlaceOrder(int requestId, string orderedby)
    {
        try
        {
            using (DatabaseContext dbContext = new DatabaseContext("myConnectionStringHere"))
            {
                var req = dbContext.Orders.Where(row => row.id == requestId).FirstOrDefault();
                if (req == null)
                    return "not found";
               
                req.status="A";
                dbContext.SaveChanges();
                return "found";
            }
        }
        catch (Exception ex)
        {
            return "error";
        }
    }

Now while Unit testing I need to make sure that it does not write anything to database, so I have to MOQ it. How can I MOQ, it contains Using block.

I know architecture could have been better and design patterns should have been followed but I am not allowed to change the structure of the application as it is a legacy application.

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Many things should be changed here:

1:

Do not implement your connection string this way, directly in the code base. Instead, DI your database into your classes.

so this pseudo code should help out with the general idea.

public void ConfigureService(IServiceCollection serviceCollection)
{
   ...

  
   string connectionString = //secure storage;
   serviceCollection.AddDbContext<DatabaseContext>(options => {

      options.UseSqlServer(connectionString);

   });

   ...
}

And then

public class OrderRepository
{
        
   private IServiceScopeFactory _serviceScopeFactory ;
        
   public OrderRepository(IServiceScopeFactory serviceScopeFactory ){
      _serviceScopeFactory = serviceScopeFactory ;
   }
   
   ...
        
        
   public string PlaceOrder(int requestId, string orderedby)
   {
      try
      {
         using (var context = serviceScopeFactory.CreateScope())
         {
            var req = context.Orders.Where(row => row.id == requestId).FirstOrDefault();
            if (req == null)
               return "not found";
                       
            req.status="A";
            context.SaveChanges();
            return "found";
         }
      }
      catch (Exception ex)
      {
         return "error";
      }
   }
    
   ...

}

if you want to make an integration test, you can then use an InMemory db to emulate whatever you want. Or you can connect to a "real" db, and do it that way.

If you want to make it a unit test, you can see at this link: How to setup a DbContext Mock

2:

returning a string saying found/not found for a order being placed, seems extremely counter productive.

if your aim is to log this information, provider a DI logger, that can log this. (Try importing the ILogger interface, it's a microsoft extension on logging, can't remember the nuget package name) should enable you to log with DI very efficiently.

If your aim is to let a possible UI display this message, there is no way the message content should originate from back-end or domain logic.

At least not like this.

Then you should make an interface for a response, and return an implementation of said interface, that exists somewhere else as a minimum but even that is a bit like peeing your pants. (And contains a UI friendly message, can contain a possible stacktrace/exception), and other possible relevant information, like what Id you were trying to place an order on etc.)

You should make it something that happens at the interface between your UI and domain logic, provided that is what the string is intended for. Where you would expect to see error handling.

3: WTF is up with the catch? you just return error? Well ? What error? you lose the stack-trace this way? Someone should be punished for that.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!