如何测试使用Maui.Storage.ISecureStorage的服务



我必须写一个集成测试,我有下面这样的服务

public class MyService: IMyService
{
private readonly ISecureStorage secureStorageService;
public MyService(ISecureStorage secureStorageService)
{
this.secureStorageService = secureStorageService;
}
}

如何在测试中创建ISecureStorage的实现?

ISecureStorage mySecureStorage = new ???????

您可以为它创建一个测试实现或使用mock,因为您不想测试真正的SecureStorage类(实际上,如果没有很多特定于平台的模糊,您就无法测试(。

选项1:使用Moq库:

using Moq;
public class MyTests
{
// this conveniently takes care of the mock implementation for you
private Mock<ISecureStorage> _secureStorageMock = new Mock<ISecureStorage>();
[Test]
public void Example()
{
//arrange
var myService = new MyService(_secureStorageMock.object);
//act
myService.DoSomething();
//assert
Assert.IsTrue(myService.Whatever);
// You can also check if a specific method has been called, like below
_secureStorageMock.Verify(s => s.SetAsync(It.IsAny<string>(), It.IsAny<string>());
}
}

选项2:创建存根实现:

public class FakeStorage : ISecureStorage
{
//TODO: implement interface with stub methods that don't actually do anything useful 
}

然后在测试中使用它:

public class MyTests
{
[Test]
public void Example()
{
//arrange
var myService = new MyService(new FakeStorage());
//act
myService.DoSomething();
//assert
Assert.IsTrue(myService.Whatever);
}
}

这只是两种方法。更高级的场景可能涉及控制容器的反转。此外,我只是假设这里使用NUnit,但xUnit也是如此。

我推荐第一种方法。它更简单、更强大,并且避免了编写伪实现或存根实现。

最新更新