Pregunta

I am having a lot of trouble understanding how to unit test my web client.

I have just finished a project using TDD for the first time - this project hd no external dependencies such as API calls or databases, it was pure C# code. I definitely saw the benefits of using TDD and I would like to continue practising it.

My next project involves writing a SOAP client. I'm struggling to get past the first test which is using a simple IClient that logs in to the API successfully.

Here is the IClient interface:

public interface IClient
{
    bool IsLoggedIn { get; }
    bool Login(out string error);
}

I have no idea how I would go about testing this. I'm thinking the unit test method would be something like Login_WithValidCredentials_ReturnsTrue, but I'm not sure how I could do this without actually simulating every possible response from the API. Is this code actually unit testable, or should this be left to an integration test.

If anyone could give me an example of a simple unit test then I would be very grateful (I am using Moq).

¿Fue útil?

Solución

Unit tests should run fast and have no external dependencies. Integration tests should cover methods that call web services.

You cannot unit test authentication logic on the client, you will have to do it on the server:

[WebMethod]
Authenticator{
 bool Login(Credentials credentials){
   return TestableClass.Login(credentials);
 }
}

now you can write a unit test on the server

Login_WithValidCredentials_ReturnsTrue(){
   // test TestableClass.login here
}

You can also test client side code that uses the service. say you have some code like this: (pardon my c#)

Class LoggerOnner{
  public LoggerOnner(IClient client, Response response){
    this.client = client
    this.page = page
  }

  Login() {
   if(this.client.Authenticate())
       response.sendPage("authenticated.aspx");
   else{
       response.sendError()
   }
  }
} 

You can test that it uses your Client correctly (how i imagine moc works :)

IClient mocClient= moq.Create(IClient).Authenticate( x-> return true );
Request moxRequest = moq.Create(Request);

LoggerOnner lo = new LoggerOnner(mocClient, mocRequest);

Assert( mocRequst.sendPage().calledWithArgs("authenticated.aspx"));

TLDR; don't unit test your Client class, make it small and test everything else

Licenciado bajo: CC-BY-SA con atribución
scroll top