[英]Unit Test a Service that depends on Blazor IJSRuntime
I'm currently writing a razor class library.我目前正在编写一个 razor class 库。 The library only contains a single Service.
该库仅包含一个服务。 The purpose of the class library is to form an API between javascript and c#. Therefore I need JSInterop.
class 库的目的是在 javascript 和 c# 之间形成一个 API。因此我需要 JSInterop。
I already wrote the interface of said service, but before I start coding any implementation of it I want to write the unit tests for it.我已经编写了所述服务的接口,但在我开始编写它的任何实现之前,我想为它编写单元测试。
The problem is, that I don't see a way to get my hands on an IJSRuntime object. I created the NUnit test project already and it has the following Setup:问题是,我没有找到一种方法来获得 IJSRuntime object。我已经创建了 NUnit 测试项目,它具有以下设置:
public partial class MyServiceTests
{
private IMyService myService;
[SetUp]
public void Setup()
{
IJSRuntime jsRuntime = null; // where do I get this from?
myService = new MyServiceImplementation(jsRuntime);
}
}
I need some way to access an IJSRuntime object.我需要一些方法来访问 IJSRuntime object。
It came to my mind that I would probably need a blazor WASM or Server application running for the unit tests to work.我想到我可能需要运行 blazor WASM 或服务器应用程序才能使单元测试正常工作。 My Service will access the local storage and manage some stuff there, so I would need a website running.
我的服务将访问本地存储并在那里管理一些东西,所以我需要一个正在运行的网站。 I tried creating those apps but sadly had no idea where to go from there.
我尝试创建这些应用程序,但遗憾的是不知道从那里到 go 的位置。
How would I be able to run my NUnit tests successfully with an IJSRuntime?我怎样才能使用 IJSRuntime 成功运行我的 NUnit 测试?
I've got something similar.我有类似的东西。 A possible way to solve this is with Mock.
解决这个问题的一种可能方法是使用 Mock。
Try to Register IJSRuntime as a dependency (Mock< IJSRuntime>).尝试将 IJSRuntime 注册为依赖项 (Mock< IJSRuntime>)。 With this, you will have a reference to an object that implements the interface.
这样,您将获得对实现该接口的 object 的引用。
And then to "Simulate" the host you need to add:然后“模拟”您需要添加的主机:
host.AddService(jsRuntimeMock.Object);
A way to implement unit testing in blazor is here , i follow that one ant it works!一种在 blazor 中实施单元测试的方法在这里,我遵循 ant 它的工作原理!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.