使用NUnit单元测试:如何判断控制器返回的Json响应真假
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_vehicleDataBusinessServicedependency so you don't need real external services)Microsoft.AspNetCore.Mvc(to work with controller types likeActionResultandJsonResult)Newtonsoft.JsonorSystem.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 whenAddModelAliasDatais called with our test model. This isolates the controller logic from external dependencies. - Casting the Result: The controller returns
ActionResult, so we cast it toJsonResultto access the underlying value that gets serialized to JSON. - Asserting the Value: We cast
result.Valuetobool(since your service returns a boolean response) and use NUnit'sAssert.IsTrue/Assert.IsFalseto 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
responsefrom 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
IVehicleDataBusinessServiceis an interface (it should be, for testability) so Moq can create a mock of it.
内容的提问来源于stack exchange,提问作者user9495286

