使用依赖注入为接口创建测试类
Create TestClass for Interface with Dependency Injection
您好,我有如下代码并使用 xUnit。我想编写 TestClass 来测试我的界面。你能告诉我怎么做吗:
- 通过 DependencyInjection 注入不同的服务来测试 class 并 运行 测试此服务。
- 准备要使用 Autofixture 和 AutoMoq 注入的对象。在注入之前,我想创建像
这样的服务
我想做这样的事情:
public ServiceTestClass
{
private ISampleService sut;
public ServiceTestClass(ISampleService service) {
this.sut = service;
}
[Fact]
public MyTestMetod() {
// arrange
var fixture = new Fixture();
// act
sut.MakeOrder();
// assert
Assert(somethink);
}
}
public class SampleService : ISampleService // ande few services which implements ISampleService
{
// ISampleUow also include few IRepository
private readonly ISampleUow uow;
public SampleService(ISampleUow uow) {
this.uow = uow;
}
public void MakeOrder() {
//implementation which use uow
}
}
你问的不是特别清楚,但是AutoFixture可以作为Auto-mocking Container. The AutoMoq Glue Library is one of many extensions that enable AutoFixture to do that. Others are AutoNSubstitute, AutoFakeItEasy等
这使您能够像这样编写测试:
[Fact]
public void MyTest()
{
var fixture = new Fixture().Customize(new AutoMoqCustomization());
var mock = fixture.Freeze<Mock<ISampleUow>>();
var sut = fixture.Create<SampleService>();
sut.MakeOrder();
mock.Verify(uow => /* assertion expression goes here */);
}
如果你把它和AutoFixture.Xunit2 Glue Library结合起来,你可以把它压缩成这样:
[Theory, MyAutoData]
public void MyTest([Frozen]Mock<ISampleUow> mock, SampleService sut)
{
var sut = fixture.Create<SampleService>();
sut.MakeOrder();
mock.Verify(uow => /* assertion expression goes here */);
}
您好,我有如下代码并使用 xUnit。我想编写 TestClass 来测试我的界面。你能告诉我怎么做吗:
- 通过 DependencyInjection 注入不同的服务来测试 class 并 运行 测试此服务。
- 准备要使用 Autofixture 和 AutoMoq 注入的对象。在注入之前,我想创建像 这样的服务
我想做这样的事情:
public ServiceTestClass
{
private ISampleService sut;
public ServiceTestClass(ISampleService service) {
this.sut = service;
}
[Fact]
public MyTestMetod() {
// arrange
var fixture = new Fixture();
// act
sut.MakeOrder();
// assert
Assert(somethink);
}
}
public class SampleService : ISampleService // ande few services which implements ISampleService
{
// ISampleUow also include few IRepository
private readonly ISampleUow uow;
public SampleService(ISampleUow uow) {
this.uow = uow;
}
public void MakeOrder() {
//implementation which use uow
}
}
你问的不是特别清楚,但是AutoFixture可以作为Auto-mocking Container. The AutoMoq Glue Library is one of many extensions that enable AutoFixture to do that. Others are AutoNSubstitute, AutoFakeItEasy等
这使您能够像这样编写测试:
[Fact]
public void MyTest()
{
var fixture = new Fixture().Customize(new AutoMoqCustomization());
var mock = fixture.Freeze<Mock<ISampleUow>>();
var sut = fixture.Create<SampleService>();
sut.MakeOrder();
mock.Verify(uow => /* assertion expression goes here */);
}
如果你把它和AutoFixture.Xunit2 Glue Library结合起来,你可以把它压缩成这样:
[Theory, MyAutoData]
public void MyTest([Frozen]Mock<ISampleUow> mock, SampleService sut)
{
var sut = fixture.Create<SampleService>();
sut.MakeOrder();
mock.Verify(uow => /* assertion expression goes here */);
}