santro
santro

Reputation: 67

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

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

[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);
    }
}

Upvotes: 0

Views: 883

Answers (1)

Philip Kendall
Philip Kendall

Reputation: 4314

While this question gives one way to solve this, my preferred solution would be different: modify SearchLogic so it is no longer static. 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. If you don't, see the linked question.

Upvotes: 1

Related Questions