Trace: » arrayfixture » setupfixture » fit_framework_implementation_differences » introducao » importantconcepts » flowmode » targetobject » writingtestsinexcel » databaseunittests » tablefixture
TableFixture
TableFixture é uma classe adicional no pacote FitNesse (esta não existe no conjunto de fixtures de FIT, porém é distribuída como parte da mesma biblioteca com FitNesse). Esta é usada para executar tabelas que não possuem uma estrutura repetitiva de maneira livre.
Formato da Tabela
Com TableFixture, você decide qual o formato e quais células são realmente usadas como parte do teste. A única limitação é que a primeira linha aponta para o nome da classe da fixture. O resto é com você. Esta classe pode ser usada para transformar relatórios, faturas ou documentos em testes. Neste exemplo, emprestado do livro Test Driven .NET Development with FitNesse , nós usamos uma fatura para verificar o cálculo de impostos.
!|TableFixtureTest| |Item|Product code|Price| |Pragmatic Programmer|B978-0201616224|34.03| |Sony RDR-GX330|ERDR-GX330|94.80| |Test Driven Development By Example|B978-0321146533|32.39| |Net Total||161.22| |Tax (10% on applicable items)||9.48| |Total||170.70|
Classe de suporte (fixture)
A classe da fixture deve estender fitnesse.fixtures.TableFixture e sobreescrever o método doStaticTable(int rows) . Neste método, processe a tabela recuperando o conteúdo das células relevantes usando getText(row, column). Você pode marcar células como corretas com right(row,column) ou incorretas com wrong(row,column,actualValue).
O exemplo a seguir verifica que o total de impostos para a fatura condiz com o valor da terceira célula da segunda linha de baixo para cima:
Código-fonte em Java
package info.fitnesse.fixturegallery;
import info.fitnesse.fixturegallery.domain.TaxCalculator;
import fitnesse.fixtures.TableFixture;
public class TableFixtureTest extends TableFixture{
protected void doStaticTable(int rows) {
TaxCalculator tc=new TaxCalculator();
double totaltax = 0;
for (int row = 1; row < rows - 3; row++)
{
totaltax += tc.GetTax(getText(row, 1),
Double.parseDouble(getText(row, 2)));
}
double taxintable = Double.parseDouble(getText(rows - 2, 2));
if (taxintable == totaltax)
right(rows - 2, 2);
else
wrong(rows - 2, 2,String.valueOf(totaltax));
}
}
Código-fonte em .Net
using System;
using System.Collections.Generic;
using System.Text;
namespace info.fitnesse.fixturegallery
{
public class TableFixtureTest : global::fitnesse.fixtures.TableFixture
{
protected override void DoStaticTable(int rows)
{
TaxCalculator tc = new TaxCalculator();
decimal totaltax = 0;
for (int row = 1; row < rows - 3; row++)
{
totaltax += tc.GetTax(GetString(row, 1),
Decimal.Parse(GetString(row, 2)));
}
decimal taxintable = Decimal.Parse(GetString(rows - 2, 2));
if (taxintable == totaltax)
Right(rows - 2, 2);
else
Wrong(rows - 2, 2, totaltax.ToString());
}
}
}
Código-fonte em Python
from info.fitnesse.fixturegallery.domain.TaxCalculator import TaxCalculator
from fitnesse.fixtures.TableFixture import TableFixture
class TableFixtureTest(TableFixture):
def doStaticTable(self, rows):
tc = TaxCalculator()
totalTax = 0.0
for row in range(1, rows - 3):
totalTax += tc.getTax(self.getText(row, 1),
float(self.getText(row, 2)))
taxinTable = float(self.getText(rows - 2, 2))
if taxinTable == totalTax:
self.right(self.getCell(rows - 2, 2))
else:
self.wrong(self.getCell(rows - 2, 2), str(totalTax))
Código-fonte em Smalltalk
'From VisualWorks®, 7.6 of March 3, 2008 on June 27, 2008 at 3:36:53 pm'!
Info.Fitnesse.Fixturegallery defineClass: #TableFixtureTest
superclass: #{Fitnesse.Fixtures.TableFixture}
indexedType: #none
private: false
instanceVariableNames: ''
classInstanceVariableNames: ''
imports: ''
category: ''!
!Info.Fitnesse.Fixturegallery.TableFixtureTest methodsFor: 'enumerating'!
doStaticTable: anInteger
| taxCalculator totalTax taxCell taxInTable |
taxCalculator := TaxCalculator new.
totalTax := 0.
2
to: anInteger - 4
do:
[:row |
totalTax := totalTax
+
(taxCalculator
taxOn: (self textAt: 3 @ row) asNumber
forCode: (self textAt: 2 @ row))].
taxCell := 3 @ (anInteger - 1).
taxInTable := (self textAt: taxCell) asNumber.
(taxInTable - totalTax) abs < 0.005
ifTrue: [self rightAt: taxCell]
ifFalse:
[self
wrongAt: taxCell
actual: totalTax printString]! !
Observações
Você também pode usar getInt para recuperar o valor da célula convertido para integer.
Em Smalltalk, #textAt:, #rightAt:, e #wrongAt:actual: assumem índices baseados em 1. Tabelas de testes em múltiplas linguages (como utilizadas aqui) usam índices baseados em 0, de maneira que uma tradução extra é preciso ser feita em #doStaticTable:
Utilização
Use TableFixture quando quiser descrever seus testes com um formato de tabela específico para seu negócio e este não for simples de se representar com nenhum outro tipo de fixture. Isto é especialmente conveniente se você já possui alguns documentos que podem ser exportados para tabelas HTML, uma vez que você pode colar HTML diretamente usando FitNesse.
Página anterior: RowFixture Próxima página: Import Página acima: Fixtures básicas de FIT
