Archive for the ‘Testy’ Category

Testujeme WS klienty

Thursday, November 5th, 2009

Chystám se přihřát si vlastní polívčičku a budu psát o tom, na čem právě ve svém volném čase dělám. Jde o knihovnu, která mi pomáhá s testováním Spring WS klientských aplikací. Jako obvykle jsem si chtěl ušetřit sám sobě práci. Jsem totiž docela nakažen testováním, takže se snažím psát unit testy skoro na všechno co dělám.

Některé části aplikace se ale testují dost špatně. Většinou jde o „okraje“ aplikace jako například JSP, komunikaci s databází, volání webových služeb nebo proprietárního kódu. Jinými slovy, pokud je testovaný kód používaný pouze mým kódem, testuje se docela dobře. Pokud je ale na rozhraní mezi mnou a uživatelem, databází nebo něčím jiným, testování se komplikuje.

Proto je důležité psát takové části co nejtenčí. Co to znamená? Vaše JSP stránky by měly být co nejjednodušší, DAO vrstva by neměla obsahovat žádnou logiku a knihovny které používáte by měly být co nejméně invazivní.

Pokud ale tyto věci na periferii chci otestovat, musím se často uchýlit k funkčním testům. K testům, které jsou sice automatizované, ale které vyžadují běžící aplikační server, Spring kontext nebo třeba databázi v paměti jako HSQL. Takové testy jsou obvykle komplikovanější a také jejich spouštění trvá výrazně děle.

Podobný problém mívám i s testy volání webové služby. Samosebou mám toto volání zapouzdřeno ve speciální vrstvě, ale i tu bych rád otestoval. Kód často vypadá podobně jako tento.

public List<Flight> getFlights(String origin, String destination) {
	//prepare request
	GetFlightsRequest request = new GetFlightsRequest();
	request.setFrom(origin);
	request.setTo(destination);
	request.setServiceClass(ServiceClass.ECONOMY);
	request.setDepartureDate(Calendar.getInstance());
	//call the service
	GetFlightsResponse response = (GetFlightsResponse)webServiceTemplate.marshalSendAndReceive(request);
	//convert response
	return response.getFlight();
}

Na začátku musím vyrobit dotaz. Obvykle musím naplnit nějaký objekt vygenerovaný XML mapovacím nástrojem. Pak zavolám službu a její odpověď musím zase převést na něco čemu rozumí moje aplikace.

Jak něco takového otestovat? Samozřejmě to jde, jenom mě to vůbec nebaví. Nejdřív potřebuji otestovat, že jsem správně vytvořil dotaz. Pokud to testuji klasicky, tak ten test vypadá podezřele stejně jako kód samotný. Hrozně mě nebaví testovat, jestli když nastavím datum odletu, tak je opravdu dobře nastaveno. Navíc je to hrozně odtrženo od požadavků. Nikdo po mě přeci nechce, abych plnil nějaký hloupý vygenerovaný objekt. Chtějí po mě, abych vygeneroval XML. Věřím sice, že XML mapovací knihova funguje správně, ale pořád mám pocit, že by bylo pěkné to otestovat nějak lépe.

Pak by bylo dobré otestovat, jestli opravdu volám tu webovou službu. Další trapný a nudný test. Nastavím mock a ověřím, jestli se opravdu zavolá. Nůůůda.

No a pak mě čeká otestovaní, jestli se dobře konvertují data z odpovědi do objektu, který má často podobnou strukturu. Další nuda.

Dá se to dělat lépe? Samozřejmě. Za pomocí našeho skvělého patentovaného přípravku, který vyčistí všechny vaše testovací skvrny bez narušení podstaty látky. Můžeme si totiž připravit požadovaný dotaz i odpověď jako XML, použít naši speciální knihovnu a napsat test například takto

@Test
public void testGetFligts()
{

	//create control
	WsMockControl mockControl = new WsMockControl();
	//teach mock what to do and create it
	WebServiceMessageSender mockMessageSender = mockControl.expectRequest("PRG-DUB-request.xml").returnResponse("PRG-DUB-response.xml").createMock();
	webServiceTemplate.setMessageSender(mockMessageSender);

	//do the test
	List<Flight> flights = client.getFlights("PRG","DUB");
	assertNotNull(flights);
	assertEquals(1, flights.size());
	assertEquals("PRG",flights.get(0).getFrom().getCode());
	assertEquals("DUB",flights.get(0).getTo().getCode());

	//verify that everything was called at least once
	mockControl.verify();
}

Krásné, jednoduché a elegantní. Popis XML dat je realizován v k tomu nejvhodnějším jazyce - v XML. Test mi i automaticky ohlídá, že jsem opravdu službu zavolal. A to nezmiňuji spoustu dalších vymožeností, které zde pro jistotu nezmiňuji, abyste ohromením neomdleli.

Pokud jste tedy zůstali při vědomí vězte, že to všechno je k mání zdarma, na adrese http://javacrumbs.net/spring-ws-test/. Jenom račte prominouti, že dokumentaci ještě nestačila býti plně dohotovena. Naše dokumentační oddělení na ní pilně pracuje tudíž se lze domnívati, že bude dohotovena v nedaleké budoucnosti. Prozatím račte vzíti v potaz příklad použití, který Vám návod jistojistě poskytne.

Test coverage – interesting only when low

Monday, September 28th, 2009

What a nice and controversial title. But I really mean it. Level of test coverage is really interesting only when it's low. Of course, we should aim for highest coverage possible, but the higher the coverage is, the less useful information it brings. Let take the following example and let's assume there are no tests for this method.

	/**
	 Adds positive numbers. If one of the parameters is negative,
	 IllegalArgumentException is thrown.
	 * @param a
	 * @param b
	 * @return
	 */
	public int addPositive(int a, int b)
	{
		if ((a<0) || (b<0))
		{
			throw new IllegalArgumentException("Argument is negative");
		}
		return a+a;
	}

No coverage - wow, that's interesting

The fact that some piece of code is not covered at all is really interesting. It either means, that we have to start writing tests at once or that the piece of code has to be deleted. Either way we know that we should do something. Moreover, we know exactly what to do. For example, we can start with the following test.

	@Test
	public void testAddition()
	{
		assertEquals(2, math.addPositive(1, 1));
	}

It will get us partial coverage like this
Partial coverage

Partial coverage - cool, I know what to test next

If I have partial coverage, I can see what other tests I am supposed to write. In our example I see that I have to test what happens if I pass in a negative numbers.

	@Test(expected=IllegalArgumentException.class)
	public void testNegative1()
	{
		math.addPositive(-1, 1);
	}
	@Test(expected=IllegalArgumentException.class)
	public void testNegative2()
	{
		math.addPositive(1, -1);
	}

Total coverage - I have no clue

Now we have 100% coverage. Well done! Unfortunately, I have no clue what to do next. I have no idea if I need to write more tests, I do not know if I have complete functional coverage. I have to stop looking at the coverage and I have to start thinking. You see, when the coverage was low it gave me lot of useful information, when it's high I am left on my own. For example I can think hard and come up with following complex test scenario.

	@Test
	public void testComplicatedAddition()
	{
		assertEquals(3, math.addPositive(1, 2));
	}

Please note, that the coverage was already 100% before I have written the test. So one more test could not make it higher. Nevertheless the test actually detected a bug that was there from the beginning. It means that 100% code coverage is not enough, we have to aim higher. We should care about functional coverage and not about code coverage!

That's also one of many reasons why we should do test driven development. Or at least test first development. If we write the tests before the code, we are forced to think from the beginning. In TDD we do not care about the coverage. We just think about the functionality, write corresponding tests and then add the code. Total coverage is automatically achieved.

In the opposite situation, when we write the code first and then add the tests as an afterthought, we are not forced to think. We can just write some tests, achieve the target coverage and be happy. Test coverage can be really deceitful. It can give us false sense of security. So please remember, test coverage is a good servant but a bad master.

Spring WS Test

Wednesday, September 2nd, 2009

Last few weeks I have been working on one of my pet projects. Its name is Spring WS Test. As the name implies, its main purpose is to simplify Spring WS tests.

Again, I am scratching my own itch. I am quite test infected and I have needed something that allows me to write functional tests of my application without having to depend on an external server. Until now, you basically had two options. This first one is to test WS client application using plain old JUnit together with a library like EasyMock. But usually this test are quite ugly and hard to read. Moreover this type of tests does not test your configuration. The second option is to create a functional test that calls an external mock service. But this solution requires you to have two JVM, its configuration is complicated and error prone.

Classical WS test

I have been looking for something in between, for something that would allow me to write functional tests using JUnit and would be able to run in the same JVM as the test. Unfortunately I have not been able to find anything similar.

Spring WS Test test

That's the reason why I have created Spring WS Test project. It's quite simple and easy even though I had to spent lot of my evenings getting it into a publishable state.

Basic configuration looks like this

<beans ...>
  <!-- Creates mock message sender -->
  <bean id="messageSender" class="net.javacrumbs.springws.test.MockWebServiceMessageSender"/>

  <!-- Injects mock message sender into WebServiceTemplate -->
  <bean class="net.javacrumbs.springws.test.util.MockMessageSenderInjector"/>

  <!-- Looks for responses on the disc based on the provided XPath -->
  <bean class="net.javacrumbs.springws.test.generator.DefaultResponseGeneratorFactoryBean">
     <property name="namespaceMap">
         <map>
            <entry key="soapenv"
                value="http://schemas.xmlsoap.org/soap/envelope/"/>
            <entry key="ns"
                value="http://www.springframework.org/spring-ws/samples/airline/schemas/messages"/>
         </map>
     </property>
     <property name="XPathExpressions">
         <list>
             <value>
                 concat(local-name(//soapenv:Body/*[1]),'/default-response.xml')
             </value>
         </list>
     </property>
 </bean>
</beans>

Here we have MockWebServiceMessageSender that replaces standard Spring WebServiceMessageSender. The replacement is done by MockMessageSenderInjector. The only other thing you have to do is to define ResponseGenerator. It's main purpose is to look for files in you test classpath and return them as mock responses.

Of course it has to decide, which file to use. By default a XPath expression is used to determine the resource name. In our example it is concat(local-name(//soapenv:Body/*[1]),'/default-response.xml'). It takes name of the payload (first soap:Body child) and uses it as a directory name. File “default-response.xml” from this directory is used as the mock response. Simple isn't it?

Of course you can define more complicated XPaths, you can use XSLT templates to generate your responses, you can validate your requests etc. More details can be found in the documentation.

Now I am looking for some end-user feedback. So please, if you are using Spring WS on the client side do not hesitate and test it. It should be stable enough to be used although there might be a bug here and there.