[英]Mock a method in another static class c#
I want to ask the best way how to mock static a method in an another class. 我想问一下如何在另一个类中模拟静态方法的最佳方法。 I know that mock is not working for a static class. 我知道模拟不适用于静态类。 Here is my Code so far. 到目前为止,这是我的代码。 I don't want to call SearchSomething() at the time because it's external interaction 我不想同时调用SearchSomething(),因为它是外部交互
public ResponseBase GetData(string searchId)
{
try
{
var request = new SearchRequest
{
SearchId = searchId
};
var response = SearchLogic.SearchSomething(request);
return response;
}
catch (Exception e)
{
return ResponseBase.ExceptionHandling(e);
}
}
public class SearchLogic(){
public static ResponseBase SearchSomething(SearchRequest request)
{
//Do Something
return new ResponseBase;
}
}
This is my UnitClass 这是我的UnitClass
[TestClass]
public class UnitClass
{
[TestMethod]
public void PositiveSearchTest()
{
//arrange
string searchId = "name";
var expected = new SearchRequest();
SearchtController search = new SearchtController();
var staticMock = new Mock<SearchLogic>();
staticMock.Setup(s => s.SearchSomething()).Returns(new ResponseBase());
//act
var actual = search.GetData(searchId);
//assert
Assert.AreEqual(actual, expected);
}
}
While this question gives one way to solve this, my preferred solution would be different: modify SearchLogic
so it is no longer static. 尽管此问题提供了一种解决方案,但我的首选解决方案将有所不同:修改SearchLogic
,使其不再是静态的。 After that, you can then mock it to your heart's content. 之后,您可以根据自己的喜好嘲笑它。 Static methods are always a complete pain for unit testing; 静态方法始终是单元测试的全部难题。 I try to use them only for situations where there is one and only one correct behaviour. 我尝试仅在只有一种正确行为的情况下使用它们。
This obviously assumes you have the ability to modify SearchLogic
. 显然,这假定您具有修改SearchLogic
的能力。 If you don't, see the linked question. 如果不这样做,请参阅链接的问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.