简体   繁体   中英

How to mock same class method in asp.net unit test

public class Controller
{

 public GetSomeData()
  {
    retun someData;
  }

 public dosomthing(Some someObj)
  {
    var getData = GetSomeData();
    return service.DosomethingElse(getData);
  }

}

I have mocked service.DosomethingElse(getData); .

I've also mocked GetSomeData(); but it returns "" (blank value) I want to return with "myData" .

I've written a TestMethod like this:

string someData ="myData";
var mockData = new Mock<Controller>();     
mockData.Setup(x => x.GetSomeData()).Returns(someData);

var mockDa = new Mock<Service>();         
mockDa.Setup(x => x.DosomethingElse(getData)).Returns(response);

Controller cObj= new Controller(mockDa.Object);

var actual = cObj.dosomthing(Some someObj);

Assert.AreEqual("expected",actual);

Please suggest how to mock GetSomeData() method of the same class.

You can't do that. You can't mock the GetSomeData for the controller you are testing. You can only mock the dependencies you inject to the class.

Think about it this way:

  1. A mock is an object with specific behavior, mocking a real class object
  2. A class object has the proper behavior

You can't have a hybrid object, a little bit of mock and a little bit of class.

By the way, even if you could, you shouldn't. When you are testing a method, you also test the other methods of the same class that are used within. This is also the way you are testing the private functions of a class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM