Is there a way to unit test against side effects?

2019-03-25 10:23发布

Any code can provide side effects. Most of the time, side effects can be a sign of bad design and/or need of refactorisation, but when unit testing I find it hard to test against. Consider the following example:

[Test]
public void TrimAll_Removes_All_Spaces()
{
    // Arrange
    var testSubject = "A    string  with     lots   of     space";
    var expectedResult = "Astringwithlotsofspace";

    // Act
    var result = testSubject.TrimAll();

    // Assert
    Assert.AreEqual(expectedResult, result);
}

that tests the following extension:

public static string TrimAll(this string str)
{
    PokeAround();

    return str.Replace(" ", "");
}

The test will pass, but there is no guard agains side effects. The effects of the call to PokeAround will go completely unnoticed.

Given that you don't know what PokeAround is - it could be anything! - how do you write a test that guards against it? Is it at all possible?

Clarification: There have been a couple of comments about the PokeAround as completely unknown being a very unlikely scenario, since we have the source when we write the test. The reason I asked this question, though, was to find a way to guard against side effects added later on. That is, when I write the test, I might have the exension method look like this:

public static string TrimAll(this string str)
{
    return str.Replace(" ", "");
}

The test passes, all is good. Then, a month later when I'm on vacation, a colleague add's the PokeAround call. I want the test I already wrote to fail because he did.

10条回答
forever°为你锁心
2楼-- · 2019-03-25 10:55

No is not possible. Testing for side effects is difficult in any testing stage. It is differrent in different projects (product development, tool development, business application development, game development etc.).

Without a complete regression test side effects cannot be found.

In a typical project (I experienced) the question for "does this change have any side effects" is often asked towards the end of the project (close to go live) or when someone wants to add a hot fix in an already productive system. I found out that without a regression test the only (still risky) quality control measure is code review.

Hope it helps.

查看更多
Viruses.
3楼-- · 2019-03-25 10:56

One technique is to randomize the order of your unit tests. If your test suite is reasonably comprehensive, then randomizing the tests' orders can reveal unexpected side effects, tests which incorrectly depend on previous tests' state, and so on.

Google Test (for C++) can do this; I don't know of other frameworks that have this feature.

查看更多
爷的心禁止访问
4楼-- · 2019-03-25 11:02

Depends what you mean by side effect - I mean, maybe PokeAround() does something important which needs to be done. How do you classify a side effect?

Anyway, there's no particular technology/technique I'm aware of to guard against side effects as such in a single unit test, but as long as you have test coverage for all of your code, any unwanted side effects will hopefully get picked up by at least one test.

BDD/Integration test tools will also help against this, as they (usually) test larger areas of functionality and not just individual classes/methods.

One thing you might want to look at is Design By Contract (DBC). This lets you specify pre and post conditions, and also invariants, so that if a method is ever called with invalid parameters, returns invalid values, or the object gets into an invalid state, an error of some kind will be thrown.

查看更多
何必那么认真
5楼-- · 2019-03-25 11:03

I'm not sure you could. After all, whether it is an intended effect or a side effect depends on the designers intention.

I'd suggest you assert that "side-effected" code is unchanged.

Also, a tool like Jester might help, but I don't think it would make a difference in your example.

查看更多
男人必须洒脱
6楼-- · 2019-03-25 11:10

No first-hand experience from me, but this might interest you: Code Contracts

http://research.microsoft.com/en-us/projects/contracts/

has a provision to put an [pure] attribute to a method and enforce side-effect freeness through runtime or compile time checks. It also allows to specify and enforce an impressing set of other contraints.

查看更多
够拽才男人
7楼-- · 2019-03-25 11:14

This is what is called sensing in Working Effectively With Legacy Code. That is, sensing the effects of calling the tested method.

Given that you don't know what PokeAround is - it could be anything!

Since we are talking about unit tests, this should hardly be true - unit testing is whitebox testing, and the code is (should be) there for you to check. Unless it is in some closed source 3rd party library, in which case you don't need to test it can't unit test it by definition (maybe you need functional/acceptance tests, but that is an entirely different matter...).

Update: so you want to make sure that future changes to your unit tested method will never have any unanticipated side effects? I think you

  1. can't,
  2. shouldn't.

You can't, because there is no sensible way to detect the lack of side effects from a method call in a real life (nontrivial) program. What you are looking for is some check that the state of the whole universe has not changed apart from this and this little thing. Even from the point of view of a humble program, that universe is vast. A method call can create/update/delete any number of local objects (many of which you can't even see from your unit test environment), touch files on available local/network file systems, execute DB requests, make remote procedure calls...

You shouldn't, because it is up to your colleague making that future change to take care of unit testing his/her change. If you don't trust that this is going to happen, you have a people or process problem, not a unit testing problem.

查看更多
登录 后发表回答