본문 바로가기
Block Chain

Truffle 테스트

by Coarti 2023. 10. 20.

2가지 테스트 방법이 있다. 콘솔 모드와 테스트 코드를 작성하는 것이다.

콘솔 모드
truffle console --network dev

배포한 Mung 스마트 콘트랙트가 확인 된후에 커서부분이 'truffle(dev)>' 로바뀌었다.

이제 deployed() 함수로 Mung 스마트 콘트랙트의 정보를 가져와 함수를 호출해보자

truffle(dev)> contract = await Mung.deployed()
truffle(dev)> contract.say();

truffle(dev)> contract.setText("haha");

 

tx : 트랜잭션 해시

receipt : 트랜잭션 정보

transationHash : 트랜잭션 교유 해시

transactionIndex : 트랜잭션이 블록에 포함될 때 몇 번째 트랜잭션으로 포함되었는지

blockHash : 블록 해시

blockNumber :  블록 번호

from : 트랜션이 발생한 EOA Ehsms CA

gasUsed : 사용된 수수료

cumulativeGasUsed : 누적 수수료

contractAddress : 스마트 콘트랙트를 배포하는 트랜잭션일 때  CA

logs, status, logbloom 값은 디앱을 만들 때 사용되지 않는다.

contract.say()

 

콘솔 모드는 ctrl + c 두번으로 빠져나올 수 있다.

테스트 코드

보다 복자한 스마트 콘트랙트를 테스트 하기에 콘솔 모드는 적합하지 않다. 따라서 라이브러를 사용한다.

truffle-assertions 라이러리는 스마트 콘트랙트 내의 함수를 검사하여 에러확인, 복잡한 테스트를 한번에 할 수 있도록 한다.

npm install --save truffle-assertions

dapp/test/ 디렉터리에 파일을 작성하여 테스트 해보자

// test_mung.js

const truffleAssert = require('truffle-assertions');
const Mung = artifacts.require("Mung");
contract("Mung", accounts => {
	// it이 실행될 때마다 스마트 콘트랙트 객체를 가져온다.
	
	before(async () => {
		this.instance = await Mung.deployed();
	});
	
	it("should be initialized wiith corrent value", async () => {
		// 스마트 콘트랙트에 정의된 text() 함수 호출
		const text = await this.instance.text();
		assert.equal(text, "hello mung", "Worng initialized vaule!");
	});
	
	it("should change the text", async () => {
		const changedText = 'haha';
		// 스마트 콘트랙트에 정의된 setText() 함수 호출
		await this.instance.setText(changedText, {from : accounts[0]});
		// 스마트 콘트랙트에 정의된 say() 함수 호출
		const text = await this.instance.say();
		assert.equal(text, changedText, "dose not change the value!");
	});
	
	it("should throw exception", async () => {
		// 스마트 콘트랙트에 정의된 errorOccur() 함수 호출
		await truffleAssert.reverts(
			this.instance.errorOccur(1, {from : accounts[0]}),
			"hello world error"
		);
	});
	it("should not throw exception", async () => {
		// 스마트 콘트랙트에 정의된 errorOccur() 함수 호출
		const rst = await this.instance.errorOccur(0, {from : accounts[0]});
		assert.equal(rst.words[0], 0, "ErrorOccur event not emitted!");
	})
	
});

it(description, test logic(function))

it == 슈트(suite), before == 훅(hook)

it(테스트 설명, 테스트 로직을 포함한 함수)

before(it 내의 코드가 실행 될 때마다 반복적으로 진행되어야 하는 과정)

before로 정의한 후 코드 실행 후 mocha가 it을 실행

truffle test --network dev

올바른 코드를 쳤다면 결과가 나오며 코드에서 잘못된 부분이 있드면 에러를 보여준다.

728x90

'Block Chain' 카테고리의 다른 글

블록체인  (0) 2023.10.25
web3.js(HttpProvider)  (0) 2023.10.20
솔리디티 언어 개발도구(트러플 v5.11.5)  (2) 2023.10.19
솔리디티 언어 개발도구(리믹스)  (0) 2023.10.19
파일 업로드/다운로드  (0) 2023.10.18