Developers often ask LLMs like OpenAI Codex to write tests for their code - and they do. The tests compile, run, and even pass, giving a sense of confidence. But how much can we really trust those tests? If an LLM only sees the source code and a few comments, does it truly understand what the software is supposed to do?Developers often ask LLMs like OpenAI Codex to write tests for their code - and they do. The tests compile, run, and even pass, giving a sense of confidence. But how much can we really trust those tests? If an LLM only sees the source code and a few comments, does it truly understand what the software is supposed to do?

The Limits of LLM-Generated Unit Tests

2025/10/24 23:46

The OpenAI Codex documentation includes a simple example prompt:

\ It sounds effortless - just ask Codex to write tests, and it will. And in most cases, it does: the tests compile, run, and even pass. Everyone seems satisfied.

\ But this raises a crucial question: are those tests actually good?

\ Let’s take a step back and think: why do we write tests? We use tests to check our code against the requirements. When we simply ask an LLM to write tests, are we sure the LLM knows all those requirements?

\ If no additional context is provided, all the LLM has is the code and, at best, inline documentation and comments. But is that enough? Let's check with several examples. To illustrate, let's start with a simple specification.

Requirements

Imagine that we have the following requirements:

  • We need to implement a new Product Service in the service layer of our application.
  • The service should have a method to retrieve the product price by product ID.
  • If the product ID is empty, an exception should be thrown with code 0.
  • The method should retrieve the product by ID from the database (using the product repository service).
  • If the product is not found, another exception should be thrown with code 1.
  • The product price should be returned.
  • The Product entity also has: ID, name, price, and cost price.

\ We will use PHP as an example, but the conclusions of this article are applicable to all languages.

Baseline Implementation

The following classes make up our starting point:

final class ProductService { public function __construct(private ProductRepository $repository) { } /** * Returns the product price or throws on error. * * @throws EmptyProductIdException When product ID is empty (code 0) * @throws ProductNotFoundException When product is not found (code 1) */ public function getProductPrice(string $productId): float { $productId = trim($productId); if ($productId === '') { throw new EmptyProductIdException(); } $product = $this->repository->findById($productId); if ($product === null) { throw new ProductNotFoundException($productId); } return $product->getPrice(); } }

\ Notice that the getProductPrice method is documented with a straightforward docblock describing its return value and expected exceptions.

\ The following supporting classes are not central to the article but are included for completeness. Feel free to skip them if you’re focusing on the main idea.

final class Product { public function __construct( private string $id, private string $name, private float $price, private float $costPrice ) { } public function getId(): string { return $this->id; } public function getName(): string { return $this->name; } public function getPrice(): float { return $this->price; } public function getCostPrice(): float { return $this->costPrice; } }

final class ProductNotFoundException extends RuntimeException { public function __construct(string $productId, ?\Throwable $previous = null) { parent::__construct("Product not found: {$productId}", 1, $previous); } }

final class EmptyProductIdException extends InvalidArgumentException { public function __construct(string $message = 'Product ID is empty', ?\Throwable $previous = null) { parent::__construct($message, 0, $previous); } }

Baseline Tests

Let's use OpenAI Codex to generate some tests for our project. I used Codex v0.25 with the GPT-5 high model.

\ For this baseline, I deliberately took the naive approach and asked:

▌Write unit tests for all public methods of the ProductService

\ Codex generated reasonable tests: two successful cases and two unsuccessful cases. It even inferred from the docblock that exceptions should carry specific error codes.

final class ProductServiceTest extends TestCase { public function testGetProductPriceReturnsPriceForExistingProduct(): void { $repo = $this->createMock(ProductRepository::class); $product = new Product('p1', 'Product 1', 19.99, 10.0); $repo->expects($this->once()) ->method('findById') ->with('p1') ->willReturn($product); $service = new ProductService($repo); $price = $service->getProductPrice('p1'); $this->assertEqualsWithDelta(19.99, $price, 0.0001); } public function testGetProductPriceTrimsIdAndReturnsPrice(): void { $repo = $this->createMock(ProductRepository::class); $product = new Product('ABC', 'Trimmed Product', 5.5, 2.0); $repo->expects($this->once()) ->method('findById') ->with('ABC') // ensure the ID is trimmed before lookup ->willReturn($product); $service = new ProductService($repo); $price = $service->getProductPrice(' ABC '); $this->assertEqualsWithDelta(5.5, $price, 0.0001); } public function testGetProductPriceThrowsOnEmptyId(): void { $repo = $this->createMock(ProductRepository::class); $service = new ProductService($repo); $this->expectException(EmptyProductIdException::class); $this->expectExceptionCode(0); $this->expectExceptionMessage('Product ID is empty'); $service->getProductPrice(' '); // becomes empty after trim } public function testGetProductPriceThrowsWhenProductNotFound(): void { $repo = $this->createMock(ProductRepository::class); $repo->expects($this->once()) ->method('findById') ->with('missing') ->willReturn(null); $service = new ProductService($repo); $this->expectException(ProductNotFoundException::class); $this->expectExceptionCode(1); $this->expectExceptionMessage('Product not found: missing'); $service->getProductPrice('missing'); } }

\ At first glance, these tests look solid. But that’s also the limitation: they only reflect what’s written in the code and comments. Do they really guard against deeper mistakes?

Mutations

To explore this, I deliberately mutated the ProductService code and asked Codex to generate tests again. Each time, I deleted the existing tests, restarted Codex to clear the context, and used the same prompt: “Write unit tests for all public methods of the ProductService.”

Case 1 -- Flipped Empty Condition

In this mutation, I inverted the condition that checks whether the product ID is empty:

- if ($productId === '') { + if ($productId !== '') {

\ Codex wrote unit tests equivalent to the previous ones, with only minor differences in line order, product names, and similar details. The tests were correct: Codex identified the error in the code, wrote appropriate tests, and even proposed a fix for the method:

Why Tests Fail - In src/Service/ProductService.php: - The condition is inverted: - Current: `if ($productId !== '') { throw new EmptyProductIdException(); }` - Intended: throw when empty/whitespace after trim. - This causes: - Non-empty IDs to wrongly throw EmptyProductIdException. - Empty/whitespace IDs to continue and hit the repository call unexpectedly. Suggested Fix (not applied) - In src/Service/ProductService.php, change the condition to: - if ($productId === '') { throw new EmptyProductIdException(); }

\ This suggests that Codex is able to handle at least obvious logical inversions.

Case 2 -- Flipped Condition During Product Search

In this mutation, I inverted the condition that checks whether the product exists in the repository:

- if ($product === null) { + if ($product !== null) {

\ The outcome was the same as in Case 1: Codex produced correct tests and proposed a fix for the bug.

Case 3 -- Return Cost Price Instead of Price

In this mutation, I changed the method to return the product’s cost price instead of its price:

- return $product->getPrice(); + return $product->getCostPrice();

\ Codex again generated four tests, but it did not realize that the method must return the product price rather than the cost price - even though this is stated in the docblock. The generated suite confirmed the mutated behavior instead of the requirement.

... public function testGetProductPriceReturnsCostPriceWhenFound(): void { $repo = $this->createMock(ProductRepository::class); $product = new Product('p1', 'Product 1', /* $price */ 19.99, /* $costPrice */ 7.49); $repo->expects($this->once()) ->method('findById') ->with('p1') ->willReturn($product); $service = new ProductService($repo); $price = $service->getProductPrice('p1'); $this->assertSame(7.49, $price); } ...

\ Unlike the earlier mutations, this one slipped through: Codex followed the code and accepted the cost price as if it were correct.

Single Coding Session Run

Before making conclusions, let’s run another experiment. This time, I asked Codex to write the code itself first, so it had more context before generating tests. All the following prompts were made within a single Codex session:

▌Create a PHP file containing a PHP class. The class is called ProductService. It has a method called getProductPrice. It receives a product ID as a string and checks that it is not empty. If it is empty, throw an exception with error code 0 (empty). It then retrieves the product by ID from the database using another service, ProductRepository. If the repository returns null, throw an exception with error code 1 (not found). Then get the product price. (Create a simple Product class with only ID, name, price, and costPrice.) All classes should be in their own files. File structure: an src folder containing Domain, Exception, Repository, and Service directories.

\ Codex produced a similar ProductService, though it didn’t add a docblock for the getProductPrice method. This made it even more interesting to see how it would handle mutations:

... public function getProductPrice(string $productId): float { if (trim($productId) === '') { throw ProductException::emptyId(); } $product = $this->productRepository->findById($productId); if ($product === null) { throw ProductException::notFound($productId); } return $product->getPrice(); } ...

\ First, I asked Codex to write tests. No surprises here: four correct unit tests were written, including checks for exception error codes in the negative cases.

\ Then I mutated the service in the same way as before. The only difference was that I slightly modified the prompt to make Codex understand there were no tests anymore:

▌Check whether tests for all public methods of ProductService still exist, and write them if they are missing

\ Codex successfully handled the inverted conditions: bugs were fixed automatically, and correct tests were generated.

\ And the most interesting part: the same happened when I replaced getPrice with getCostPrice:

Fixes Made - Restored missing test file tests/Service/ProductServiceTest.php. - Corrected ProductService::getProductPrice to return $product->getPrice().

\ So, as expected, even without additional context from a docblock, Codex was able to generate correct tests and repair the code, relying on the initial requirements given at the start of the session.

Conclusion

These experiments show that the naive approach to writing tests with an LLM does not deliver the expected results. Yes, tests will be generated -- but they will simply mirror the current code, even if that code contains bugs. An LLM can identify obvious logic errors, but when the code involves complex business rules or formulas, the generated tests will not meet the goals of unit testing.

\ Here are a few practical lessons:

  • Provide more context. Add inline comments and documentation blocks before generating tests. This may help, but it still cannot guarantee correct unit tests or meaningful bug detection.
  • Write code and tests in the same session. If the LLM writes the code and the tests together, it has a better chance of enforcing the original requirements, as the single-session run demonstrated.
  • Review everything. Unit tests from an LLM should never be committed blindly -- they require the same careful review as hand-written tests.

\ LLMs can certainly help with testing, but without clear requirements and human review, they will only certify the code you already have -- not the behavior you actually need.

:::warning Disclaimer: Although I'm currently working as a Lead Backend Engineer at Bumble, the content in this article does not refer to my work or experience at Bumble.

:::

\

Disclaimer: The articles reposted on this site are sourced from public platforms and are provided for informational purposes only. They do not necessarily reflect the views of MEXC. All rights remain with the original authors. If you believe any content infringes on third-party rights, please contact service@support.mexc.com for removal. MEXC makes no guarantees regarding the accuracy, completeness, or timeliness of the content and is not responsible for any actions taken based on the information provided. The content does not constitute financial, legal, or other professional advice, nor should it be considered a recommendation or endorsement by MEXC.
Share Insights

You May Also Like

US Spot ETH ETFs Witness Remarkable $244M Inflow Surge

US Spot ETH ETFs Witness Remarkable $244M Inflow Surge

BitcoinWorld US Spot ETH ETFs Witness Remarkable $244M Inflow Surge The world of digital assets is buzzing with exciting news! US spot ETH ETFs recently experienced a significant milestone, recording a whopping $244 million in net inflows on October 28. This marks the second consecutive day of positive movement for these crucial investment vehicles, signaling a growing appetite for Ethereum exposure among mainstream investors. What’s Fueling the Latest US Spot ETH ETFs Inflow? This impressive influx of capital into US spot ETH ETFs highlights a clear trend: institutional and retail investors are increasingly comfortable with regulated crypto investment products. The figures, reported by industry tracker Trader T, show a robust interest that could reshape the market. Fidelity’s FETH led the charge, attracting a substantial $99.27 million. This demonstrates strong confidence in Fidelity’s offering and Ethereum’s long-term potential. BlackRock’s ETHA wasn’t far behind, securing $74.74 million in inflows. BlackRock’s entry into the crypto ETF space has been closely watched, and these numbers confirm its growing influence. Grayscale’s Mini ETH also saw significant action, pulling in $73.03 million. This new product is quickly gaining traction, offering investors another avenue for Ethereum exposure. It’s important to note that while most products saw positive flows, Grayscale’s ETHE experienced a net outflow of $2.66 million. This might suggest a shift in investor preference towards newer, perhaps more cost-effective, spot ETF options. Why Are US Spot ETH ETFs Attracting Such Significant Capital? The appeal of US spot ETH ETFs is multifaceted. For many investors, these products offer a regulated and accessible way to gain exposure to Ethereum without directly owning the cryptocurrency. This removes some of the complexities associated with digital asset management, such as setting up wallets, managing private keys, or dealing with less regulated exchanges. Key benefits include: Accessibility: Investors can buy and sell shares of the ETF through traditional brokerage accounts, just like stocks. Regulation: Being regulated by financial authorities provides a layer of security and trust that some investors seek. Diversification: For traditional portfolios, adding exposure to a leading altcoin like Ethereum through an ETF can offer diversification benefits. Liquidity: ETFs are generally liquid, allowing for easy entry and exit from positions. Moreover, Ethereum itself continues to be a powerhouse in the blockchain space, underpinning a vast ecosystem of decentralized applications (dApps), NFTs, and decentralized finance (DeFi) protocols. Its ongoing development and significant network activity make it an attractive asset for long-term growth. What Does This US Spot ETH ETFs Trend Mean for Investors? The consistent positive inflows into US spot ETH ETFs could be a strong indicator of maturing institutional interest in the broader crypto market. It suggests that major financial players are not just dabbling but are actively integrating digital assets into their investment strategies. For individual investors, this trend offers several actionable insights: Market Validation: The increasing capital flow validates Ethereum’s position as a significant digital asset with real-world utility and investor demand. Potential for Growth: Continued institutional adoption through ETFs could contribute to greater price stability and potential upward momentum for Ethereum. Observing Investor Behavior: The shift from products like Grayscale’s ETHE to newer spot ETFs highlights how investors are becoming more discerning about their investment vehicles, prioritizing efficiency and cost. However, it is crucial to remember that the crypto market remains volatile. While these inflows are positive, investors should always conduct their own research and consider their risk tolerance before making investment decisions. A Compelling Outlook for US Spot ETH ETFs The recent $244 million net inflow into US spot ETH ETFs is more than just a number; it’s a powerful signal. It underscores a growing confidence in Ethereum as an asset class and the increasing mainstream acceptance of regulated cryptocurrency investment products. With major players like Fidelity and BlackRock leading the charge, the landscape for digital asset investment is evolving rapidly, offering exciting new opportunities for both seasoned and new investors alike. This positive momentum suggests a potentially bright future for Ethereum’s integration into traditional financial portfolios. Frequently Asked Questions (FAQs) What is a US spot ETH ETF? A US spot ETH ETF (Exchange-Traded Fund) is an investment product that allows investors to gain exposure to the price movements of Ethereum (ETH) without directly owning the cryptocurrency. The fund holds actual Ethereum, and shares of the fund are traded on traditional stock exchanges. Which firms are leading the inflows into US spot ETH ETFs? On October 28, Fidelity’s FETH led with $99.27 million, followed by BlackRock’s ETHA with $74.74 million, and Grayscale’s Mini ETH with $73.03 million. Why are spot ETH ETFs important for the crypto market? Spot ETH ETFs are crucial because they provide a regulated, accessible, and often more familiar investment vehicle for traditional investors to enter the cryptocurrency market. This can lead to increased institutional adoption, greater liquidity, and enhanced legitimacy for Ethereum as an asset class. What was Grayscale’s ETHE outflow and what does it signify? Grayscale’s ETHE experienced a net outflow of $2.66 million. This might indicate that some investors are shifting capital from older, perhaps less efficient, Grayscale products to newer spot ETH ETFs, which often offer better fee structures or direct exposure without the previous trust structure limitations. If you found this article insightful, consider sharing it with your network! Your support helps us bring more valuable insights into the world of cryptocurrency. Spread the word and let others discover the exciting trends shaping the digital asset space. To learn more about the latest Ethereum trends, explore our article on key developments shaping Ethereum institutional adoption. This post US Spot ETH ETFs Witness Remarkable $244M Inflow Surge first appeared on BitcoinWorld.
Share
2025/10/29 11:45
First Ethereum Treasury Firm Sells ETH For Buybacks: Death Spiral Incoming?

First Ethereum Treasury Firm Sells ETH For Buybacks: Death Spiral Incoming?

Ethereum-focused treasury company ETHZilla said it has sold roughly $40 million worth of ether to fund ongoing share repurchases, a maneuver aimed at closing what it calls a “significant discount to NAV.” In a press statement on Monday, the company disclosed that since Friday, October 24, it has bought back about 600,000 common shares for approximately $12 million under a broader authorization of up to $250 million, and that it intends to continue buying while the discount persists. ETHZilla Dumps ETH For BuyBacks The company framed the buybacks as balance-sheet arbitrage rather than a strategic retreat from its core Ethereum exposure. “We are leveraging the strength of our balance sheet, including reducing our ETH holdings, to execute share repurchases,” chairman and CEO McAndrew Rudisill said, adding that ETH sales are being used as “cash” while common shares trade below net asset value. He argued the transactions would be immediately accretive to remaining shareholders. Related Reading: Crypto Analyst Shows The Possibility Of The Ethereum Price Reaching $16,000 ETHZilla amplified the message on X, saying it would “use its strong balance sheet to support shareholders through buybacks, reduce shares available for short borrow, [and] drive up NAV per share” and reiterating that it still holds “~$400 million of ETH” on the balance sheet and carries “no net debt.” The company also cited “recent, concentrated short selling” as a factor keeping the stock under pressure. The market-structure logic is straightforward: when a digital-asset treasury trades below the value of its coin holdings and cash, buying back stock with “coin-cash” can, in theory, collapse the discount and lift NAV per share. But the optics are contentious inside crypto because the mechanism requires selling the underlying asset—here, ETH—to purchase equity, potentially weakening the very treasury backing that investors originally sought. Death Spiral Incoming? Popular crypto trader SalsaTekila (@SalsaTekila) commented on X: “This is extremely bearish, especially if it invites similar behavior. ETH treasuries are not Saylor; they haven’t shown diamond-hand will. If treasury companies start dumping the coin to buy shares, it’s a death spiral setup.” Skeptics also zeroed in on funding choices. “I am mostly curious why the company chose to sell ETH and not use the $569m in cash they had on the balance sheet last month,” another analyst Dan Smith wrote, noting ETHZilla had just said it still holds about $400 million of ETH and thus didn’t deploy it on fresh ETH accumulation. “Why not just use cash?” The question cuts to the core of treasury signaling: using ETH as a liquidity reservoir to defend a discounted equity can be read as rational capital allocation, or as capitulation that undermines the ETH-as-reserve narrative. Beyond the buyback, a retail-driven storyline has rapidly formed around the stock. Business Insider reported that Dimitri Semenikhin—who recently became the face of the Beyond Meat surge—has targeted ETHZilla, saying he purchased roughly 2% of the company at what he views as a 50% discount to modified NAV. He has argued that the market is misreading ETHZilla’s balance sheet because it still reflects legacy biotech results rather than the current digital-asset treasury model. Related Reading: Ethereum Emerges As The Sole Trillion-Dollar Institutional Store Of Value — Here’s Why The same report cites liquid holdings on the order of 102,300 ETH and roughly $560 million in cash, translating to about $62 per share in liquid assets, and calls out a 1-for-10 reverse split on October 15 that, in his view, muddied the optics for retail. Semenikhin flagged November 13 as a potential catalyst if results show the pivot to ETH generating profits. The company’s own messaging emphasizes the discount-to-NAV lens rather than a change in strategy. ETHZilla told investors it would keep buying while the stock trades below asset value and highlighted a goal of shrinking lendable supply to blunt short-selling pressure. For Ethereum markets, the immediate flow effect is limited—$40 million is marginal in ETH’s daily liquidity—but the second-order risk flagged by traders is behavioral contagion. If other ETH-heavy treasuries follow the playbook, selling the underlying to buy their own stock, the flow could become pro-cyclical: coins are sold to close equity discounts, the selling pressures spot, and wider discounts reappear as equity screens rerate to the weaker mark—repeat. That is the “death spiral” scenario skeptics warn about when the treasury asset doubles as the company’s signal of conviction. At press time, ETH traded at $4,156. Featured image created with DALL.E, chart from TradingView.com
Share
2025/10/29 12:00