logo
down
shadow

Unit test controller with IConfiguration using Moq and Mock setup returns null


Unit test controller with IConfiguration using Moq and Mock setup returns null

Content Index :

Unit test controller with IConfiguration using Moq and Mock setup returns null
Tag : chash , By : Reiner
Date : November 26 2020, 03:04 PM

With these it helps This is more of a design issue wrapped in an XY problem.
Really should not be injecting IConfiguration. Based on how the configuration is using by the controller what you should have done was register the settings with the service collection in startup
//...

AppSettings appSettings = Configuration.Get<AppSettingsModel>().AppSettings;

services.AddSingleton(appSettings);

//...
//...

private readonly AppSettings appSettings = null;
public CarController(AppSettings appSettings , ICarPairingTable carPairingTable, ICarDealerSettingsTable settingsTable) {
    this.appSettings = appSettings;
    PairingTable = carPairingTable;
    DealerSettingsTable = settingsTable;
}

//...
[HttpGet]
public async Task<ActionResult> Get(string id){
    string DealerId = await PairingTable.GetDealerId(id);
    if (string.IsNullOrEmpty(DealerId)) {
        var result = new ReturnResult {
            status = "Fail",
            data = "ID is invalid"
        };
        return NotFound(result);
    }

    SettingsInfo info = await DealerSettingsTable.GetSettingsInfo(DealerId);
    if (info == null) {
        var result = new ReturnResult {
            status = "Fail",
            data = "Not Found"
        };
        return NotFound(result);
    }
    var result = new ReturnResult {
        status = "Success",
        data = info
    };
    return Ok(result);
}
[Fact]
public async Task Should_Return_Ok_ReturnRsult() {
    //Arrange
    var id = "456";
    var dealerId = "123";
    SettingsInfo expected = new SettingsInfo() {
        DealerId = dealerId,
        Name="Dealer1"
    };

    var pairingMock = new Mock<ICarPairingTable>();
    pairingMock.Setup(p => p.GetDealerId(id)).ReturnsAsync(dealerId);

    var dealerSettingsMock = new Mock<ICarDealerSettingsTable>();
    dealerSettingsMock.Setup(p => p.GetSettingsInfo(dealerId)).ReturnsAsync(() => expected);

    CarController controller = new CarController(new AppSettings(),  pairingMock.Object, dealerSettingsMock.Object);

    //Act
    var actionResult = await controller.Get(id);
    var actual = actionResult as OkObjectResult;

    //Assert (using FluentAssertions)

    actual.Should().NotBeNull();

    actual.Value.Should().BeOfType<ReturnResult>();

    var actualResult = actual.Value as ReturnResult;

    actualResult.data.Should().BeEquivalentTo(expected);        
}

Comments
No Comments Right Now !

Boards Message :
You Must Login Or Sign Up to Add Your Comments .

Share : facebook icon twitter icon

Unit Test on MVC 3 Controller returns null for results, but I can see them in Immediate Window


Tag : asp.net-mvc-3 , By : apple
Date : March 29 2020, 07:55 AM
this will help Had this problem before, you are not using the same versions of System.Web.Mvc in your projects. You must reference the same version of System.Web.Mvc both in your main project and unit test project.

Grails 2.3 controller method returns JSON gets null back in unit test


Tag : json , By : bikefixxer
Date : March 29 2020, 07:55 AM
To fix this issue render writes directly to the reponse - see here.
Try like this:
void "test that the controller can greet in JSON"() {
    when: 
    controller.greet()

    then:
    response.text == '{"greeting":"Hey there"}'
    response.json.greeting == "Hey there"  //another option
}

Moq: Mock SetUp method only returns null during test


Tag : chash , By : Mark W
Date : March 29 2020, 07:55 AM
wish help you to fix your issue You didn't set any behavior on the Add method of mockDbSet.
Add:(This line initialize the method to return the given person)
mockDbSet.Setup(x => x.Add(It.IsAny<Person>()))
         .Returns <Person>(p => p);
var mockDbSet = new Mock<DbSet<Person>>();
mockDbSet.Setup(x => x.Add(It.IsAny<Person>()))
         .Returns<Person>(p => p);

var mockContext = new Mock<IHiveTiesContext>();
mockContext.Setup(x => x.People)
           .Returns(mockDbSet.Object);
...

Unit Test Mock Controller, C# Do I need to Mock HTTPContext? What methods do I mock?


Tag : chash , By : CrookedNumber
Date : March 29 2020, 07:55 AM
may help you .
Question: What methods am I supposed to be mocking and testing within the controller?
    [Test]
    public void SearchforAccount_ReturnSearchAccount()
    {
        //Arrange
        var mockAccountsManager = A.Fake<IAccountsManager>();
        var mockCallerInfoManager = A.Fake<ICallerInfoManager>();
        const string SearchTerm = "google"; // Use the passed in parameter in the CallTo setup

        //Define search parameter
        AccountRequest mockAccountRequest = new AccountRequest
        {
            SearchTerm = SearchTerm
        };

        List<Account> expected = new List<Account> { new Account() }; // What we expect to get back

        A.CallTo(() => mockAccountsManager.GetAllWithNameContaining(SearchTerm, A<string>.Ignored)).Returns(expected); // mock the call made in the controller

        using (var accountsController = new AccountController2(mockAccountsManager, mockCallerInfoManager))
        {
            //Act
            List<Account> returnedAccounts = accountsController.Search(mockAccountRequest);

            //Assert
            Assert.AreSame(expected, returnedAccounts);
        }
    }
public CallerInfo GetFrom(HttpRequest request)
{
    return ExtractCallerInfo(request.QueryString);
}

public CallerInfo GetFromHttpContext()
{
    return GetFrom(HttpContext.Current.Request);
}

Mock in unit test returns null at LINQ.Where


Tag : chash , By : Raghaw
Date : March 29 2020, 07:55 AM
it fixes the issue The Linq Where is working fine. The searchedBeam is being assigned null because of the attempt to cast from the mocked interface to the concrete type.
                          right here
                              |
                              v
Treatment searchedBeam = (Treatment)InputData.Treatments.
    Where(beam => beam.TimeStamp == sortingList[j + i * rangeOfBeams]).FirstOrDefault();
[SetUp]
public override void Init() {
    base.Init();

    // --- Create Plan Mock
    // some code here

    // --- Create Treatment Mock
    DateTime time1 = new DateTime(2000, 01, 01, 12, 00, 00);
    DateTime time2 = new DateTime(2000, 01, 01, 13, 00, 00);

    var treatMock1 = new Treatment {
        TimeStamp = time1
    };
    var treatMock2 = new Treatment {
        TimeStamp = time2
    };

    treatGroupMock1 = new Mock<ITreatmentGroup>();
    treatGroupMock1.Setup(_ => _.Treatments).Returns(new List<ITreatment>() { treatMock1, treatMock2 });
}
Related Posts Related QUESTIONS :
  • Why is Array.Length an int, and not an uint
  • How do I make event callbacks into my win forms thread safe?
  • Genealogy Tree Control
  • WCF Service - Backward compatibility issue
  • Binary patch-generation in C#
  • Tab Escape Character?
  • When do Request.Params and Request.Form differ?
  • The imported project "C:\Microsoft.CSharp.targets" was not found
  • Numeric Data Entry in WPF
  • Print a Winform/visual element
  • C# logic order and compiler behavior
  • When to use an extension method with lambda over LINQtoObjects to filter a collection?
  • How to make a button appear as if it is pressed?
  • C# and Arrow Keys
  • How do you resolve a domain name to an IP address with .NET/C#?
  • Should the folders in a solution match the namespace?
  • How can I evaluate C# code dynamically?
  • CSharpCodeProvider Compilation Performance
  • How can I create Prototype Methods (like JavaScript) in C#.Net?
  • DataTable Loop Performance Comparison
  • CSV string handling
  • What is the best way to do unit testing for ASP.NET 2.0 web pages?
  • High availability
  • What to use for Messaging with C#
  • Accessing a Dictionary.Keys Key through a numeric index
  • ConfigurationManager.AppSettings Performance Concerns
  • What Are Some Good .NET Profilers?
  • Is this a good way to determine OS Architecture?
  • How to create a tree-view preferences dialog type of interface in C#?
  • Searching directories for tons of files?
  • Can I have a method returning IEnumerator<T> and use it in a foreach loop?
  • Why can't I have abstract static methods in C#?
  • Displaying ad content from Respose.WriteFile()/ Response.ContentType
  • Convert integers to written numbers
  • Absolute path back to web-relative path
  • How can we generate getters and setters in Visual Studio?
  • Bringing Window to the Front in C# using Win32 API
  • Possible to "spin off" several GUI threads? (Not halting the system at Application.Run)
  • Reading a C/C++ data structure in C# from a byte array
  • How should I translate from screen space coordinates to image space coordinates in a WinForms PictureBox?
  • Setting Objects to Null/Nothing after use in .NET
  • Converting ARBG to RGB with alpha blending
  • Is it better to create Model classes or stick with generic database utility class?
  • Passing enum type to Converter with integer value
  • Pool of objects with objects that are already on the scene in advance
  • StatusBar text fade-out when binding using Caliburn.Micro
  • Queryfilter on ApplicationUser in OnModelCreating in ApplicationDbContext creates StackOverflowException
  • How to get record form a different table based on a value from first table with linq expression?
  • Show data in Grid from returned model
  • Using Attributes to Override Data Model Conventions
  • Basic OOP console calculator, result Error
  • Compositon and Repository pattern
  • Multiple using statements with if condition
  • How do i increase a number by 1 in every line that contain the number 1
  • Add binding to elements that are created in codebehind
  • How to add a column in an existing AspNetUsers table
  • Order a list of elements with another list of doubles
  • How to setup a NuGet package to copy content files to output build directory?
  • In SignalR Core using ChannelWriter: Do I need to call TryComplete twice if there's an exception?
  • C# GetProcessesByName: issue with colon
  • shadow
    Privacy Policy - Terms - Contact Us © scrbit.com