且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

我应该出于什么原因嘲笑?

更新时间:2022-02-21 01:48:13

首先,确定您的目标是什么,要测试什么. Fortega指出,您的测试不是在测试Validate类方法,而是创建一个行为类似该方法的模拟程序.确定要测试的对象(被测试的对象)以及执行测试所需的对象(协作者),然后查看协作者并确定它们是易于创建的东西还是您需要的东西嘲笑他们.

First, decide what your objective is and what you want to test. Your test isn't testing your Validate class method, it's creating a mock that behaves like that method, as Fortega points out. Identify what it is you are testing (the object under test) and what it is you need in order to perform the test (the collaborators), then look at the collaborators and decide whether they are things that are easy to create or if you need to mock them.

对于此类不依赖任何东西的类,我建议完全不使用模拟.这里没有需要模拟的东西,测试可以这样写:

For something like this class which has no dependencies on anything, I would recommend doing without mocks entirely. There is nothing here that needs mocking, the test can be written like this:

import static org.junit.Assert.*;

public class ValidateTestCase {

    @Test
    public void testHappyPath() throws Exception {
        Validate.stateNotNull("", "");
    }

    @Test
    public void testNullMessage() throws Exception {
        try {
            Validate.stateNotNull(null, null);
            fail();
        }
        catch (IllegalStateException e) {
            String expected = "Exception message is a null object!"
            assertEquals(expected, e.getMessage());
        }
    }

    @Test(expected=IllegalStateException.class)
    public void testNullObject() throws Exception {
        Validate.stateNotNull(null, "test");
    }
}

这会告诉您代码是否满足您的要求.

and that tells you whether the code does what you want it to.

除非存在某种依赖关系,否则不要嘲笑该依赖关系,因为它是外部资源(例如文件系统或数据库)或某些复杂的子系统,因此要避免引入该测试.模拟框架可能非常有用,但是它们增加了复杂性,它们可能过度指定了要测试的事物的行为,使测试变得脆弱,并使测试难以阅读.如果可以的话,请不要使用它们.

Don't mock unless there is some dependency that you want to avoid introducing to the test due to it being either an external resource (like a filesystem or database) or some complex subsystem. The mock frameworks can be very useful but they add complexity, they can over-specify the behavior of the things they are testing, making the tests brittle, and they can make tests hard to read. Do without them if you can.