APIController使用Mock进行Nunit测试时,需要使用接口实例的情况。
创始人
2024-09-07 08:00:28
0
  1. 创建一个接口:
public interface IUserService {
    User Get(int id);
    IEnumerable GetAll();
}
  1. 创建一个实现IUserService接口的类:
public class UserService : IUserService {
    public User Get(int id) {
        // 从数据库中获取用户
        // ...
    }

    public IEnumerable GetAll() {
        // 从数据库中获取所有用户
        // ...
    }
}
  1. 在ApiController中注入IUserService:
public class UserController : ApiController {
    private readonly IUserService _userService;
    
    public UserController(IUserService userService) {
        _userService = userService;
    }

    public IHttpActionResult Get(int id) {
        var user = _userService.Get(id);
        if (user == null) {
            return NotFound();
        }
        return Ok(user);
    }

    public IHttpActionResult GetAll() {
        var users = _userService.GetAll();
        if (users.Any()) {
            return Ok(users);
        }
        return NotFound();
    }
}
  1. 创建一个MockUserService,实现IUserService接口:
public class MockUserService : IUserService {
    public User Get(int id) {
        // 从内存中获取用户
        // ...
    }

    public IEnumerable GetAll() {
        // 从内存中获取用户
        // ...
    }
}
  1. 在Nunit测试中使用MockUserService实例进行测试:
[TestFixture]
public class UserControllerTests {
    [Test]
    public void Get_Should_Return_User() {
        // Arrange
        var userService = new MockUserService();
        userService.Add(new User { Id = 1, Name = "张三" });
        var controller = new UserController(userService);

        // Act
        IHttpActionResult result = controller.Get(1);

        // Assert
        Assert.IsNotNull(result);
        var content = result as OkNegotiatedContentResult;
        Assert.IsNotNull(content);
        Assert.AreEqual("张三", content.Content.Name);
    }

    [Test]
    public void GetAll_Should_Return_All_Users() {
        // Arrange
        var userService = new MockUserService();
        userService.Add(new User { Id = 1, Name = "张三" });

相关内容

热门资讯

盘点一款!新版WPK(WepO... 盘点一款!新版WPK(WepOke)外挂透明挂辅助APP(透视)解密教程(有挂方式)-哔哩哔哩;小薇...
一分钟了解(WPK透视挂)外挂... 一分钟了解(WPK透视挂)外挂透明挂辅助工具(辅助挂)的确真的有挂(2023已更新)(哔哩哔哩)1、...
透明安装(aapoker辅助)... 透明安装(aapoker辅助)外挂透明挂辅助app(透视)发牌规律(有挂细节)-哔哩哔哩准备好在aa...
透视数据(WPK)外挂透明挂辅... 透视数据(WPK)外挂透明挂辅助APP(透视)辅助透视(有挂方针)-哔哩哔哩;实战中需综合运用上述技...
必备科技!线上wpk德州(we... 必备科技!线上wpk德州(wepokE)外挂透明挂辅助app(辅助挂)wpk教程(有挂秘籍)-哔哩哔...
透明神器(线上wpk德州)外挂... 透明神器(线上wpk德州)外挂透明挂辅助工具(透视)其实是真的有挂(2023已更新)(哔哩哔哩);一...
透明透视(wEpoke)外挂透... 1、透明透视(wEpoke)外挂透明挂辅助工具(透视)透视辅助(有挂助手)-哔哩哔哩;该软件可以轻松...
热点推荐(aapoker教程)... 热点推荐(aapoker教程)外挂透明挂辅助脚本(透视)发牌规律(证实有挂)-哔哩哔哩;值得一提的是...
5分钟了解!Wepoke修改器... 5分钟了解!Wepoke修改器(wepOKE)外挂透明挂辅助脚本(辅助挂)揭秘攻略(有挂讲解)-哔哩...
盘点一款(新版WPK)外挂透明... 盘点一款(新版WPK)外挂透明挂辅助插件(透视)竟然是真的有挂(2025已更新)(哔哩哔哩);亲,其...