简体   繁体   中英

Logic of calling a method to be tested in TDD

As I am new in tdd development, I tried mocking for the first time and I have a doubt regarding the same.

Consider following example:

here goes Business

public class MyEmail
{
    public bool SendEmail()
    {
           Email code goes here 
           return true;
    }
}

Another class 

public class Customer

{
  public bool Addcustomer()
  {
     MyEmail obj = new MyEmail();
     obj.SendEmail();
     return true;
  }
}

Here goes my test for Addcustomer

[TestMethod()]
public void AddCustomerTest()
{
  Mock<Myemail> objemail = new Mock<Myemail>();

  objemail.Setup(x=>x.SendEmail()).Returns(true);

customer obj = new Customer(); // Created object of customer class because I want to test the methos that contains in this class.

Now My question Lies here??

 obj.AddCustomer(objemail.Object);

Please check above statement. We have called a method in class Customer with a parameter but actually that method does not accepts any param. But that method is not receiving any compilation error or run time error. How is it possible?

Is it only happening in test methods because ideally this should not be acceptable by compiler as per c# basics.

and moreover suppose if my Addcustomer method in class Customer is already having a defination like below. Then what should I do???

  public bool Addcustomer(int Anynumber)
  {
     MyEmail obj = new MyEmail();
     obj.SendEmail(Anynumber));
     return true;
  }

  Assert.AreEqual(obj.AddCustomer(), true);
}

I'm not sure if I understand you correctly and what the problem is, but here is a better way of setting up the classes:

    public class Customer
    {
      private MyEmail _myEmail;
      public void Customer(MyEmail myEmail)
      {
        _myEmail = myEmail;
      }

      public bool Addcustomer()
      {     
         _myEmail.SendEmail();
         return true;
      }
    }

[TestMethod()]
public void AddCustomerTest()
{
  Mock<Myemail> objemail = new Mock<Myemail>();

  objemail.Setup(x=>x.SendEmail()).Returns(true);
  customer obj = new Customer(objemail.Object);

  //Assert something
}

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