Writing test for my application. Would like to test connection with exeption handling, for now I have created method which works and looks like :
[Test]
public void TestCreateConnection()
{
Connection testConnection = new Connection();
connection.CreateConnection(correctURL, IDName + connection.ApiKey, connection.ContentType, connection.MediaType, connection.Get, false, "name");
testConnection.CreateConnection(correctURL, IDName + connection.ApiKey, connection.ContentType, connection.MediaType, connection.Get, false, "name");
}
In the finall version working on smth which will catch exception - WebExeption. Already have it in try / catch block inside my method which is about to create connection, it works ofc. But need it in my test as well. I was thinking it should looks like :
[Test]
[ExpectedException(typeof(WebException))]
public void TestCreateConnection()
{
Connection testConnection = new Connection();
connection.CreateConnection(correctURL, IDName + connection.ApiKey, connection.ContentType, connection.MediaType, connection.Get, false, "name");
testCconnection.CreateConnection(correctURL, IDName + connection.ApiKey, connection.ContentType, connection.MediaType, connection.Get, false, "name");
Assert.Catch<WebException>(() => connection.CreateConnection("test", IDName + connection.ApiKey, connection.ContentType, connection.MediaType, connection.Get, false, "name"););
}
Like we can see i changed first arg of the method which is URL address, it will couse the web exeption. How can i write it in correct way ?
I don't think there is anything wrong in your approach of testing the exception. I do suggest, however, that you split your test into two tests - one for the case where you get a valid connection, and one for the case where you get a bad connection.
This is without knowing the exact details of how you implemented the test connection. If you have some internal component in charge of creating the connection, and your code is a wrapper around it, then you should consider passing the internal component in as an Interface and mocking its behavior.