【发布时间】:2021-07-04 17:44:21
【问题描述】:
我最近开始在网络上编程。我有如下问题:我有一个带数据库的web应用,数据层和业务逻辑层都写了,业务逻辑层的nunit测试怎么写,我在网上找到可以用moq(mock) ,但我完全不明白怎么做。数据库通过 DbContext 访问。项目链接:(https://github.com/Aleksandr34nov/WebApiApp),我这里补充一下。这里我试着写了一个测试:
namespace BuissnessLayerTests
{
[TestFixture]
class SongTests
{
private static DbContextOptions<ASContext> options;
private static ASContext context = new ASContext(options);
private static EFSongsRepository _songRep = new EFSongsRepository(new SongDataAccess(context));
[Test]
public void GetItemByIdTest()
{
Song song = new Song();
song.SongTitle = "In The End";
song.AlbumId = -1;
int id = _songRep.AddItem(song);
Song? testSong = _songRep.GetItemById(id);
_songRep.DeleteItem(song);
if (song.Equals(testSong))
{
Assert.Pass();
}else
{
Assert.Fail();
}
}
}
}
搞错了: Mistake
我不完全理解它是如何工作的,请告诉我如何正确编写测试。 这是项目结构: Struct
有实体(歌曲和专辑):
using System;
using System.Collections.Generic;
using System.Text;
namespace Domain
{
public class Song
{
public int SongId { get; set; }
public string SongTitle { get; set; }
public int AlbumId { get; set; }
public Album Album { get; set; }
public Song() { }
}
}
using System;
using System.Collections.Generic;
using System.Text;
namespace Domain
{
public class Album
{
public int AlbumId { get; set; }
public List<Song> SongList { get; set; }
public string Title { get; set; }
public string Artist { get; set; }
public Album() { }
}
}
这是上下文:
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.EntityFrameworkCore.Design;
using Domain;
namespace DataLayer
{
public class ASContext : DbContext
{
public DbSet<Album> Albums { get; set; }
public DbSet<Song> Songs { get; set; }
public ASContext(DbContextOptions<ASContext> options) : base(options) { }
}
public class EFDBContextFactory : IDesignTimeDbContextFactory<ASContext>
{
public ASContext CreateDbContext(string[] args)
{
var optionsBuilder = new DbContextOptionsBuilder<ASContext>();
optionsBuilder.UseSqlServer("Server=(localdb)\\mssqllocaldb;Database=AlbumsSongsDatabase;Trusted_Connection=True;MultipleActiveResultSets=true", b => b.MigrationsAssembly("DataLayer"));
return new ASContext(optionsBuilder.Options);
}
}
}
【问题讨论】:
标签: c# asp.net .net entity-framework nunit