Testing Java Sockets

后端 未结 4 1190
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-13 07:11

I\'m developing a network application and I want to get unit testing right. THIS time we\'ll do it, you know? :)

I\'m have trouble testing network connections, thou

4条回答
  •  一个人的身影
    2020-12-13 07:19

    I'm going to answer your question as asked instead of redesigning your class (others have that covered, but the basic question on the class as written is stil valid).

    Unit testing never tests anything outside the class being tested. This hurt my brain for a while--it means unit test does not in any way prove that your code works! What it does is prove that your code works the same way it did when you wrote the test.

    So that said you want a unit test for this class but you also want a functional test.

    For the unit test you have to be able to "Mock out" the communications. To do this instead of creating your own socket, fetch one from a "Socket factory", then make yourself a socket factory. The factory should be passed in to the constructor of this class you are testing. This is actually not a bad design strategy--you can set the hostname and port in the factory so you don't have to know about them in your communication class--more abstract.

    Now in testing you just pass in a mock factory that creates mock sockets and everything is roses.

    Don't forget the functional test though! Set up a "test server" that you can connect to, send some messages to the server and test the responses you get back.

    For that matter, you probably want to do even deeper functional tests where you write a client that sends the REAL server some scripted commands and tests the results. You probably even want to create a "Reset state" command just for functional testing. Functional tests actually ensure that entire "Functional units" work together as you expect--something that many unit testing advocates forget.

提交回复
热议问题