You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用NUnit单元测试:如何判断控制器返回的Json响应真假

Testing Your Controller's JSON Response in NUnit

Hey there! Since you're new to unit testing, let's walk through exactly how to test your AddModelAliasData controller method and verify whether the returned JSON is true or false. We'll break this into simple, actionable steps.

First, Set Up Your Dependencies

You'll need a few NuGet packages to make this work:

  • NUnit (the core testing framework)
  • Moq (to mock your _vehicleDataBusinessService dependency so you don't need real external services)
  • Microsoft.AspNetCore.Mvc (to work with controller types like ActionResult and JsonResult)
  • Newtonsoft.Json or System.Text.Json (to parse the JSON response value if needed)

Step 1: Mock the Business Service

Your controller depends on _vehicleDataBusinessService, so we'll use Moq to create a mock version of this service. This lets us control exactly what it returns during tests, without relying on real databases or external logic.

Step 2: Write the Test Cases

We'll cover two main success scenarios (returning true and false) plus a validation failure scenario (since your method throws an error if ModelState is invalid).

Example Test Code

using NUnit.Framework;
using Moq;
using Microsoft.AspNetCore.Mvc;
using YourNamespace; // Replace with your actual project namespace

[TestFixture]
public class YourControllerTests
{
    private Mock<IVehicleDataBusinessService> _mockBusinessService;
    private YourController _controller; // Replace with your actual controller name

    [SetUp]
    public void Setup()
    {
        // Initialize the mock service
        _mockBusinessService = new Mock<IVehicleDataBusinessService>();
        
        // Create the controller instance with the mocked service injected
        _controller = new YourController(_mockBusinessService.Object);
    }

    [Test]
    public void AddModelAliasData_ValidModel_ReturnsJsonTrue()
    {
        // Arrange
        var testModel = new ModalAliasModel(); // Populate with valid data if your model requires it
        _mockBusinessService.Setup(s => s.AddModelAliasData(testModel))
                           .Returns(true); // Tell the mock to return true

        // Act
        var result = _controller.AddModelAliasData(testModel) as JsonResult;

        // Assert
        Assert.IsNotNull(result, "Expected a JsonResult but got null");
        var responseValue = (bool)result.Value; // Cast the JSON payload to a boolean
        Assert.IsTrue(responseValue, "Expected the JSON response to be true");
    }

    [Test]
    public void AddModelAliasData_ValidModel_ReturnsJsonFalse()
    {
        // Arrange
        var testModel = new ModalAliasModel();
        _mockBusinessService.Setup(s => s.AddModelAliasData(testModel))
                           .Returns(false); // Mock returns false this time

        // Act
        var result = _controller.AddModelAliasData(testModel) as JsonResult;

        // Assert
        Assert.IsNotNull(result);
        var responseValue = (bool)result.Value;
        Assert.IsFalse(responseValue, "Expected the JSON response to be false");
    }

    [Test]
    public void AddModelAliasData_InvalidModel_ThrowsBusinessException()
    {
        // Arrange
        var testModel = new ModalAliasModel();
        // Manually add an error to ModelState to trigger validation failure
        _controller.ModelState.AddModelError("SomeProperty", "Invalid value");

        // Act & Assert
        var exception = Assert.Throws<BusinessException>(() => 
            _controller.AddModelAliasData(testModel));
        Assert.AreEqual("COMMON_ERROR", exception.Message);
    }
}

Key Explanations

  • Mock Setup: We use _mockBusinessService.Setup(...) to define exactly what the service returns when AddModelAliasData is called with our test model. This isolates the controller logic from external dependencies.
  • Casting the Result: The controller returns ActionResult, so we cast it to JsonResult to access the underlying value that gets serialized to JSON.
  • Asserting the Value: We cast result.Value to bool (since your service returns a boolean response) and use NUnit's Assert.IsTrue/Assert.IsFalse to verify it matches our expectation.
  • ModelState Validation: For the invalid scenario, we manually add an error to the controller's ModelState to trigger the exception your method throws when validation fails.

Quick Notes

  • If your response from the service isn't a raw boolean (e.g., it's a wrapper object with a boolean property), adjust the casting to match that object type, then check its specific property.
  • Make sure your IVehicleDataBusinessService is an interface (it should be, for testability) so Moq can create a mock of it.

内容的提问来源于stack exchange,提问作者user9495286

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 11:12:51