Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9209163
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 18, 20262026-06-18T00:46:39+00:00 2026-06-18T00:46:39+00:00

I am just starting to dive into unit testing and am just starting to

  • 0

I am just starting to dive into unit testing and am just starting to grasp the repository pattern and IoC. I don’t think I fully understand it, however, because parts of it seems a bit silly. Let me explain.

My Controller:

public class UserProfileController : ApiController
{
    private IUserProfileRepository repository;

    // Optional constructor, passes repository, allows dependency injection
    public UserProfileController(IUserProfileRepository userProfileRepository)
    {
        this.repository = userProfileRepository;
    }

    // GET api/UserProfile
    // Returns a list of all users
    public IEnumerable<UserProfile> Get()
    {
        // Only Admins can see a list of users
        if (Roles.IsUserInRole("Admin"))
        {
            return repository.Get();
        }
        else
        {
            throw new HttpResponseException(
                new HttpResponseMessage(HttpStatusCode.Forbidden)
                {
                    ReasonPhrase = "Administrator access required"
                });
        }
    }

// Other methods, etc.

(note that I have a dependency, Roles.IsUserInRole(“Admin”) that I can’t figure out how to abstract, which causes some problems).

My typical repo interface:

public interface IUserProfileRepository : IDisposable
{
    IEnumerable<UserProfile> Get();
    // Other methods, etc.
}

Repo:

public class UserProfileRepository : IUserProfileRepository, IDisposable
{
    private OfootContext context;

    public UserProfileRepository(OfootContext context)
    {
        this.context = context;
    }

    public IEnumerable<UserProfile> Get()
    {
        return context.UserProfiles.AsEnumerable();
    }

// ... More code

So everything seems fine, I’ve abstracted my business access layer from my business logic and now I can create a fake repository to run unit tests.

Fake Repo:

public class FakeUserProfileRepository : IUserProfileRepository, IDisposable
{
    private List<UserProfile> context;

    public FakeUserProfileRepository(List<UserProfile> context)
    {
        this.context = context;
    }

    public IEnumerable<UserProfile> Get()
    {
        return context.AsEnumerable();
    }

and Test:

[TestMethod]
public void GetUsers()
{
    // Arrange
    var items = new List<UserProfile>()
    {
        new UserProfile
        {
            UserId = 1,
            Username = "Bob",
        },
        new UserProfile
        {
            UserId = 2,
            Username = "Bob2",
        }
    };

    FakeUserProfileRepository repo = new FakeUserProfileRepository(
        items);
    UserProfileController controller = new UserProfileController(
        repo);

    // Act
    IEnumerable<UserProfile> result = controller.Get();

    // Assert
    Assert.IsNotNull(result);
}

Now that we’re on the same page (and feel free to point out any ‘code smells’), here are my thoughts:

  1. The fake repository requires that I re-implement all of my Entity Framework logic and change it to dealing with a List object. This is more work and more links in the chain that I will need to debug.
  2. If the unit test does pass, it doesn’t say anything about my code that accesses EF, so my application could still fail. This just means I need to test my EF code separately and have it hit a database.
  3. From #1, if the unit test is not testing the EF code, then it’s just dealing with my authentication, authorization, and User creation code in my controller. Which it can’t, because the WebSecurity and Roles classes hit my database.
  4. If I’m going to use a database to test EF code (point #2) and need a database to test the controller code (for authentication and authorization, point #3) then why bother even abstracting with a repository. Why don’t I just abstract the context (using IContext or something?) and wire in a test database that is populated using the DropCreateDatabaseAlways class?

If I do figure out a way to abstract the user account garbage out, I am still just shuffling around code and creating more code (maybe even twice as much? Since I need to create fakes) where I could just replace the Context.

My question is: What am I missing? Is it an overall concept or is it something specific?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-18T00:46:40+00:00Added an answer on June 18, 2026 at 12:46 am

    You’re on the right track. It’s always painful getting things up and running, but you’ll find it pays off down the road.

    Rather than create “fake” objects, I recommend a framework like Moq. It allows you to set up the behavior you need at the time of the test, rather than re-implementing whole interfaces. For example, in your test you could simply write:

        Mock<IUserProfileRepository> mockUserRepo = new Mock<IUserProfileRepository>();
        var items = new List<UserProfile>()
        {
            new UserProfile
            {
                UserId = 1,
                Username = "Bob",
            },
            new UserProfile
            {
                UserId = 2,
                Username = "Bob2",
            }
        };
       mockUserRepo.Setup(m => m.Get().Returns(items.AsEnumerable());
       UserProfileController controller = new UserProfileController(
            mockUserRepo.Object);
    
        // Act
       IEnumerable<UserProfile> result = controller.Get();
       //Now you can keep varying the mock response by changing the Setup(), so now 
       //check for null response handling, 0 items, exceptions etc...
    

    The net result of all this effort is that you’ve totally isolated the testing to your Controller, there are no DB dependencies and you can easily vary the inputs without writing classes, but rather playing with the mock setup.

    If you follow this simple architectural pattern, you gain awesome testability and a clear separation of concerns. As things get more complex in your system, you can take advantage of a DI container like Unity.

    On the authentication piece, I recommend creating Attributes you can decorate your methods with, like ASP.Net MVC uses: [Authorization(Roles=”Admin”)] as an example. This creates another useful cross-cutting pattern that keeps the Auth stuff decoupled from the business logic in the controller.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

So I'm just starting to dive into Node and I understand that the I/O
I'm just starting to dive into ASP.net MVC3. I come from a Django background.
I'm just starting to dive into some basic Android development and have been experimenting
I'm just now starting to dive into IF statements in R . From what
I'm starting to dive into TFS 2012 and I have a basic understanding of
Just starting with Django and have began creating an application for test purposes. However,
Just starting to look into WCF and came across the WSDualHttpBinding binding. I have
Just starting out with rails and I have a question. My grasp on associations
Hey - just starting out trying to get some openGL into my iphone app
Just starting to look into using LinqDataSource for a GridView and I’m looking for

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.