First of all you need to understand what unit testing is. Unit testing is when you test the logic, you don't use databases, services or anything like that, it only tests the logic. If the project is not written to be unit testable then the chances of it being testable are almost zero and will require a lot of refactoring. Let's say you have a bank web service with a Transfer method
[WebMethod]
public bool Transfer(decimal amount, string sourceAccount, string destinationAccount)
{
return true;
}
This is probably what you have at the moment so what you need to do is create a class that handles the logic and a class that handles the data access.
public interface IBank
{
bool Subtract(decimal amount, string account);
bool Add(decimal amount, string account);
}
public class Bank : IBank
{
public bool Subtract(decimal amount, string account)
{
return true;
}
public bool Add(decimal amount, string account)
{
return true;
}
}
And the class with the business logic
public class BankService
{
private IBank bank;
public BankService() : this(new Bank())
{
}
public BankService(IBank bank)
{
this.bank = bank;
}
public bool Transfer(decimal amount, string sourceAccount, string destinationAccount)
{
this.bank.Subtract(amount, sourceAccount);
this.bank.Add(amount, destinationAccount);
return true;
}
}
It is this class and this class only we'll be unit testing. Update your web method to use this class instead of having the code inside the webmethod
[WebMethod]
public bool Transfer(decimal amount, string sourceAccount, string destinationAccount)
{
BankService bs = new BankService();
return bs.Transfer(amount, sourceAccount, destinationAccount);
}
So the webmethod uses BankService and that is where the transfer logic is, and that BankService uses Bank to do the database updates. The logic we need to test is that when transferring money the money is subtracted from one and added to the other, so we'll mock the IBank class (I'm using moq in this example) so that we don't need the database and there is no database access and we'll test that the appropriate methods have been called, so the unit test will look like this
Mock<IBank> bank = new Mock<IBank>();
BankService bankService = new BankService(bank.Object);
bankService.Transfer(10, "111", "222");
bank.Verify(b => b.Subtract(10, "111"));
bank.Verify(b => b.Add(10, "222"));
That's the basics of what it is you need to do, you need to break things into classes that do dedicated tasks and have those tasks implement interfaces so that they can be mocked at any level. In reality your BankService class itself would implement IBankService in case you needed to mock the entire thing.