I'm trying to add a counter to subsection titles. For example:

1. Design tests

1.1 Test 1. A test

1.2 Test 2. Another test

2. Functional tests

2.1 Test 3. Yet another test

1.1 Test 1. A test (and the other two tests will be 2 and 3)

but then the section in the document will be:

1.1 Test 4. A test (and the other two tests will be 5 and 6)

Here is a sample code:

\documentclass{article}

\newcounter{test}
\DeclareRobustCommand{\newtest}[1]{
\refstepcounter{test} \label{test:#1}
Test \thetest #1
}

\begin{document}
\title{Test example}

\maketitle

\clearpage

\tableofcontents

\clearpage

\section{Design tests}
\subsection{\newtest{A test}}
\subsection{\newtest{Another test}}
\section{Functional tests}
\subsection{\newtest{Yet another test}}
\end{document}

• Welcome to TeX.SX! In my point this is a bad idea! What is the purpose of the counter at all? – user31729 Jun 14 '16 at 10:26
• @ChristianHupfer Thanks. The purpose is to count the tests that will appear in several sections of the document. Also, every test is intended to have several subsections (like test description, procedure, ...) – Enrique Jun 14 '16 at 12:50

This approach prevents the \refstepcounter code if it's not executed in the \tableofcontents, by using a conditional named \ifnotintoc, being set to false at the beginning of the \tableofcontents.

This prevents the generation of the same label again (unless \newtest is used again after resetting of the test counter!)

In the ToC stage, the already written label is extracted with \getrefnumber (requires refcount package). (A \ref usage would work too, but there would be a hyperlink then, if hyperref is used in addition).

Be sure to say \notintoctrue after \tableofcontents!

\documentclass{article}

\usepackage{refcount}
\usepackage[bookmarksopen,bookmarksopenlevel=3]{hyperref}

\newcounter{test}

\makeatletter

\newif\ifnotintoc

\DeclareRobustCommand{\newtest}[1]{%
\ifnotintoc
\refstepcounter{test}\label{test:#1}%
Test \thetest\ #1%
\else
Test \getrefnumber{test:#1}\ #1%
\fi
}

\makeatother

\begin{document}

\title{Test example}

\maketitle

\clearpage

\tableofcontents
\notintoctrue
\clearpage

\section{Design tests}
\subsection{\newtest{A test}}
\subsection{\newtest{Another test}}
\section{Functional tests}
\subsection{\newtest{Yet another test}}
\end{document}


• Thanks. The only problem I've experienced with this solution is that the PDF bookmarks have a wrong text. Instead of "Test 1. A test", the bookmark is "testTest1. A test" – Enrique Jun 14 '16 at 14:10
• @Enrique: Not for me. I can post a screenshot of the bookmarks too. – user31729 Jun 14 '16 at 14:13

This can be achieved by resetting counter next to Table of Contents:

   \tableofcontents
\setcounter{test}{0}

• This does not solve the problem with multiply defined lables! – user31729 Jun 14 '16 at 10:42
• I agree this... – Kumaresh PS Jun 14 '16 at 10:45