'How to write a Test for methods working with HashMaps
I'm trying to write a test methode like:
import junitparams.JUnitParamsRunner;
import junitparams.Parameters;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.util.Arrays;
import static org.junit.Assert.assertEquals;
@RunWith(JUnitParamsRunner.class)
public class TestBinaryIntArraySearchImpl {
private IntArraySearcher binaryIntArraySearch;
@Before
public void before(){
binaryIntArraySearch = new BinaryIntArraySearchImpl();
}
@After
public void after(){
binaryIntArraySearch = null;
}
@Test
@Parameters({
"1 , 1 ,true",
"3-4 , 8 ,false",
"1-3 , 7 ,false",
"1-2-3-4-5-6-7-8 , 9 ,false",
"3-6-7-7-8-9 , 7 ,true",
"7-7-7-7-7 , 7 ,true"
})
public void testSearch(String unSorted, int numbersToSearch, boolean found) {
int[] unSortedArray =
Arrays.stream(unSorted.split("-"))
.map(Integer::valueOf)
.mapToInt(Integer::intValue)
.toArray();
assertEquals(
found,
binaryIntArraySearch.search(unSortedArray, numbersToSearch)
);
}
@Test
public void testSearch_emptyList() {
int[] emptyList = {};
assertEquals(
false,
binaryIntArraySearch.search(emptyList, 3)
);
}
for a methode working with a hashmap. But because my knowledge about writing tests isn't that good and my research didn't realy pay of I thought i make a question and maybe one of u guys can help me with my problem.
For example here're two of the methods i want to test:
Map<String, Integer> marketplaceMaterialStock = new HashMap<>();
public boolean checkMaterialStock(String materialOne, int amountOne, String materialTwo, int amountTwo){
if(this.marketplaceMaterialStock.get(materialOne)>=amountOne && this.marketplaceMaterialStock.get(materialTwo) >= amountTwo){
return true;
}
return false;
}
public boolean buyMaterial(String materialOne, int amountOne , String materialTwo , int amountTwo){
int newStockOne;
int newStockTwo;
if(this.marketplaceMaterialStock.get(materialOne)>=amountOne && this.marketplaceMaterialStock.get(materialTwo) >= amountTwo){
newStockOne = this.marketplaceMaterialStock.get(materialOne) - amountOne;
newStockTwo = this.marketplaceMaterialStock.get(materialTwo) - amountTwo;
this.marketplaceMaterialStock.replace(materialOne, this.marketplaceMaterialStock.get(materialOne) , newStockOne);
this.marketplaceMaterialStock.replace(materialTwo, this.marketplaceMaterialStock.get(materialTwo) , newStockTwo);
return true;
}
return false;
}
maybe somebody can help me out or can give me an address where something like this is explained.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
