У меня проблема с библиотекой Mockito mockingMockito spy ссылается на неправильный объект
Мой класс испытаний Junit4 с 2 тестовыми наборами.
тест один:
@Test
public void test1()
{
Class class = new Class();
Class classSpy = Mockito.spy(class);
Mockito.when(classSpy.getExpectedValue()).thenReturn("expected_one");
}
и второй тест:
@Test
public void test2()
{
Class class = new Class();
Class classSpy = Mockito.spy(class);
Mockito.when(classSpy.getExpectedValue()).thenReturn("expected_two");
}
и у меня есть проверяемый класс:
public class TestableClass
{
x = class.getExpectedValue();
//some code
}
И проблема:
1 - I запустить тестовый класс с помощью test1()
и test2()
На первом работают test1()
отладчика указует x = "expected_one"
все в порядке - это ожидаемое поведение
2 - test2 работает я поставил точку останова в моей проверяемой классе в соответствии с й .. и x = "expected_one"
Кажется, Mockito использует ту же ссылку для шпионажа объекта (classSpy
) в обоих теста. !!
заранее спасибо за помощь
пс: я использую Mockito 1.9.0 и JRE 6.0.370.6
пс: у меня есть обычный метод SetUp:
@Before
public void setUp(){
testableClass = new TestableClass();
}
ps3: полный набор тестов :
package xxx;
import java.io.File;
import java.io.IOException;
import junit.framework.Assert;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.mockito.Mockito;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import xxx.testdata.JUnitConstants;
import xxx.testdata.JUnitUtils;
import xxx.testdata.MockNode;
@SuppressWarnings("deprecation")
public class MONodeModifierTest
{
private MONodeModifier moNodeModifier;
private Document doc;
static File file;
@Before
public void setUp(){
doc = JUnitUtils.CreateXMLDocumentFromFile(file);
moNodeModifier = new MONodeModifier(doc);
}
@Test
public void createNodeTest(){
Node inputMoNode = new MockNode();
boolean nodeisCreated = moNodeModifier.createMONode(inputMoNode, doc);
Assert.assertTrue(nodeisCreated);
}
@Test
public void removeNodeTest(){
final Node inputMoNode = new MockNode();
NodeList nodeList = new NodeList(){
@Override
public Node item(int index)
{
return inputMoNode;
}
@Override
public int getLength()
{
return 1;
}};
boolean nodeisRemoved = moNodeModifier.removeMONode(inputMoNode,nodeList);
Assert.assertTrue(nodeisRemoved);
}
@Test
public void updateMONodeWithPname(){
Node node = new MockNode();
NodeList nodeListMock = Mockito.mock(NodeList.class);
Node nodeSpy = Mockito.spy(node);
Mockito.when(nodeSpy.getChildNodes()).thenReturn(nodeListMock);
Mockito.when(nodeSpy.getNodeName()).thenReturn("p");
Mockito.when(nodeListMock.getLength()).thenReturn(1);
Mockito.when(nodeListMock.item(Mockito.anyInt())).thenReturn(nodeSpy);
boolean nodeisUpdated = moNodeModifier.updateMONode(nodeSpy, nodeListMock);
Assert.assertTrue(nodeisUpdated);
Mockito.verify(nodeSpy).setTextContent(Mockito.anyString());
}
@Test
public void updateMONodeWithNonEmptyListName(){
Node node = new MockNode();
NodeList nodeListMock = Mockito.mock(NodeList.class);
Node nodeSpy = Mockito.spy(node);
Mockito.when(nodeSpy.getChildNodes()).thenReturn(nodeListMock);
Mockito.when(nodeSpy.getNodeName()).thenReturn("list");
Mockito.when(nodeListMock.getLength()).thenReturn(1).thenReturn(1);
Mockito.when(nodeListMock.item(Mockito.anyInt())).thenReturn(nodeSpy);
boolean nodeisUpdated = moNodeModifier.updateMONode(nodeSpy, nodeListMock);
Assert.assertTrue(nodeisUpdated);
Mockito.verify(nodeSpy).replaceChild(Mockito.any(Node.class),Mockito.any(Node.class));
}
@Test
public void updateNonExistMONodeType(){
Node node = new MockNode();
Node nodeSpy = Mockito.spy(node);
NodeList nodeListMock = Mockito.mock(NodeList.class);
Mockito.when(nodeSpy.getChildNodes()).thenReturn(nodeListMock);
Mockito.when(nodeSpy.getNodeName()).thenReturn("p");
Mockito.when(nodeSpy.getNodeType()).thenReturn((short) 1).thenReturn((short) 1).thenReturn((short) 1).thenReturn((short) 2);
Mockito.when(nodeListMock.getLength()).thenReturn(1);
Mockito.when(nodeListMock.item(Mockito.anyInt())).thenReturn(nodeSpy);
boolean nodeisCreated = moNodeModifier.updateMONode(nodeSpy, nodeListMock);
Assert.assertTrue(nodeisCreated);
Mockito.verify(nodeSpy).appendChild(Mockito.any(Node.class));
}
@BeforeClass
public static void prepareFileBeforeTests() throws IOException
{
file = JUnitUtils.copyFile(
new File("xx.xml"), new File("testfile.xml"));
}
@AfterClass
public static void deleteFileAfterTests()
{
JUnitUtils.deleteFile(new File(
"testfile.xml"));
}
}
и класс шпионаж:
package xxx.testdata;
import org.w3c.dom.Attr;
import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.TypeInfo;
import org.w3c.dom.UserDataHandler;
public class MockNode implements Node,Element,Attr
{
@Override
public NodeList getChildNodes()
{
return new NodeList(){
@Override
public int getLength()
{
return 1;
}
@Override
public Node item(int index)
{
return new MockNode();
}};
}
@Override
public String getNodeName()
{
return "name";
}
@Override
public short getNodeType()
{
return 1;
}
}
и updateMONode() метод:
boolean updateMONode(Node inputMoNode, NodeList targetNodeList)
{
String inputMoDn = Utils.getAttrValue(inputMoNode, "distName");
for(int i = 0; i < targetNodeList.getLength(); i++)
{
Node targetMoNode = targetNodeList.item(i);
String targetMoDn = Utils.getAttrValue(targetMoNode, "distName");
if((targetMoNode.getNodeType() == Node.ELEMENT_NODE) &&
(inputMoNode.getNodeType() == Node.ELEMENT_NODE))
{
if(Utils.compareDns(targetMoDn, inputMoDn))
{
NodeList parameters = inputMoNode.getChildNodes();
boolean isParameterChanged = false;
boolean isChanged = false;
for(int j = 0; j < parameters.getLength(); j++)
{
if((parameters.item(j).getNodeType() == Node.ELEMENT_NODE))
isChanged =
updateParamNode(
parameters.item(j), targetMoNode,
inputMoDn);
if(isChanged)
{
isParameterChanged = isChanged;
isUpdatedParameterNode = false;
}
}
if(isParameterChanged)
{
return true;
}
}
}
}
return false;
}
Вы уверены, что можете использовать это объявление: Class class = new ClassMock() ;? – Ioan
Вы переопределяете 'setUp()' для сброса всех переменных перед новым тестом? – qiGuar
@loan: извините за название класса, которое он может предоставить, чтобы неправильно понять. Я изменил его – mynameismarcin