开发人员区

Advanced Software Development with MATLAB

Failure is the first step to trying

The official guidance on test-driven development is to follow thered-green-refactor循环:

  1. Write a test that fails.
  2. 让它通过。
  3. 重构。

但是,从失败的测试开始,重点是什么?为了确保您写了正确的测试!最近,我遇到了一些意外的行为,突出了这一点。

Imagine you have a图书馆that aggregates项目。AnItemcan be either aBookor aFilm,但不是同时。如果我们创建一个图书馆in "book mode", it should initially contain an emptyBook。If we create it in "film mode", it should initially contain an emptyFilm。让我们开始编写测试以捕获书籍模式行为:

classdeftLibrary < matlab.unittest.TestCasemethods(测试)功能bookModeInitialisesToEmptyBook(testCase) lib = Library(Mode="book");testcase.verifyequal(lib.items,book.empty(1,0))endendend

(TheName=value名称配对的语法是introduced in R2021a。It’s interchangeable with the classic(…,“名称”,值)句法。)

Let’s run the test. We expect it to fail because图书馆不存在。

We’ll skip over the steps of creating a blank class definition, the subsequent test failures due to a missing constructor with input arguments and a public项目property, and iteratively adding them in.

Instead, let's jump to the implementation of图书馆that makes our test pass:

classdef图书馆特性= Book.empty项(:1)项目endmethods功能lib = Library(nvp)参数nvp.Mode (1,1) string {mustBeMember(nvp.Mode,["book" "film"])} ="book"endendendend

We run the test and see that it passes:

So far, so good. Now we write a test to capture film mode:

功能filmModeInitialisesToEmptyFilm(testCase) lib = Library(Mode=“电影”);testCase.verifyEqual(lib.Items,Film.empty(1,0))end

We run the test:

And… it passes!?

Why is it passing? We can use the debugger to inspectlib.items手动看到它是空的Book和not an emptyFilm。After some investigation, we find thatverifyEqual依靠isequalisequalconsiders two empties of different classes to be equal under some circumstances.

Whether or not this behaviour ofisequalis correct, the important point for us is that we’ve written the wrong test! Our implementation could have been wrong and we wouldn’t have known. We would have achieved fullcoveragebut our test would not have been contributing useful information.

We therefore need to rewrite our test to catch this issue:

功能filmModeInitialisesToEmptyFilm(testCase) lib = Library(Mode=“电影”);testCase.verifyEmpty(lib.Items) testCase.verifyClass(lib.Items,?Film)end

Let’s run the updated test:

The test now fails and we can continue with our implementation, confident that our test will only pass when our implementation is correct.




Published with MATLAB® R2022a

|
  • print
  • send email

コメント

コメントを残すには、ここMATHWORKSアカウントアカウントアカウントアカウントサインインするする新しい新しい新しい新しい新しいアカウントアカウントアカウントアカウント作成し。。。