Mockito test when(repository.findById()).thenReturn(object with custom attributes) - unit-testing

So I was writing a couple of unit tests, some of them were made for testing missing attributes of Document. When using of when(repository.findOne(id)).thenReturn(DOCUMENT_WITHOUT_SOMETHING), those DOCUMENT_WITHOUT_SOMETHING were final objects with predefined attributes, depending on test cases.
Let's say, there could be a document without name, so when loading document by id the method was returning null with some log message. So I created a class of test data DocumentServiceTestData, where those necessary objects and attributes were declared. Is it a good approach or you suggest something more clear, without need of making new class?
I will try to write a simplified code of what I did.
Document
public class Document {
private String name;
private String applicant;
private String sign;
private boolean signed;
public boolean isSigned() {return signed;}
public String getApplicant() {return applicant;}
public String getName() {return name;}
public String getSign() {return sign;}
public void setSigned(boolean signed) {this.signed = signed;}
public void setApplicant(String applicant) {this.applicant = applicant;}
public void setName(String name) {this.name = name;}
public void setSign(String sign) {this.sign = sign;}
}
DocumentService
#Service
public class DocumentService {
private static final Logger LOG = LoggerFactory.getLogger(DocumentService.class);
private DocumentRepository documentRepository;
public Document loadDocument(Long docId) {
Document document = documentRepository.findByIdOrFail(docId);
if(document.getName() == null) {
LOG.info("There is no name for document, returning null");
return null;
}
if(document.getSign() == null) {
LOG.info("The document is not signed, returning null");
return null;
}
return document;
}
}
DocumentServiceTestData
public class DocumentServiceTestData {
public static final Long DOC_ID = 1L;
public static final String APPLICANT = "Applicant";
public static final String DOC_NAME = "Document";
public static final String SIGN = "Sign";
public static final Document DOCUMENT_WITHOUT_NAME;
public static final Document DOCUMENT_WITHOUT_SIGN;
static {
DOCUMENT_WITHOUT_NAME = makeDocument(null, APPLICANT, SIGN, true);
DOCUMENT_WITHOUT_SIGN = makeDocument(DOC_NAME, APPLICANT, null, false);
}
private static Document makeDocument(String name, String applicant, String sign, boolean signed) {
Document document = new Document();
document.setName(name);
document.setApplicant(applicant);
document.setSign(sign);
document.setSigned(signed);
return document;
}
}
DocumentServiceTest
#RunWith(MockitoJUnitRunner.class)
#Category(MockTest.class)
public class DocumentServiceUnitTest {
#InjectMocks
private DocumentService service;
#Mock
private DocumentRepository documentRepository;
#Test
public void testLoadDocument_notSigned(){
when(documentRepository.findByIdOrFail(DOC_ID)).thenReturn(DOCUMENT_WITHOUT_SIGN);
Document document = service.loadDocument(DOC_ID);
Assert.assertNull(document);
}
#Test
public void testLoadDocument_notNamed(){
when(documentRepository.findByIdOrFail(DOC_ID)).thenReturn(DOCUMENT_WITHOUT_NAME);
Document document = service.loadDocument(DOC_ID);
Assert.assertNull(document);
}
}
To sum up, I would like to know - if there is another way to test those cases, when I need to return specified objects while calling repository.findById(id).
PS: keep in mind that this is very simplified, those tests I've made were much more complex. If there is any information missing please let me know, I will try to clarify things. Thanks

Related

xunit not taking long strings from constants into theory (.net core)

Can someone tell me why XUnit is only recognizing the second constant in the example below? The below code will only run the Theory with the second constant. I'm completely stumped.
namespace DocumentStore.IntegrationTests
{
public static class Constants
{
public const string Test1 = "https://documentstore1.dev.namespace.net/v2/service.svc/basicNoAuth";
public const string Test2 = "https://documentstore1.dev.namespace.net/v2/service.svc";
}
public class Tests
{
[Theory]
[InlineData(Constants.Test1)]
[InlineData(Constants.Test2)]
public void ExampleTest(string url)
{
var test = url;
}
}
}
I also found that if a parameter value is too long xUnit treats the two theories as the same because the truncated values are the same. Super lame but here is a hack I used to get around it. I added a theoryIndex to make sure they are unique
namespace DocumentStore.IntegrationTests
{
public static class Constants
{
public const string Test1 = "https://documentstore1.dev.namespace.net/v2/service.svc/basicNoAuth";
public const string Test2 = "https://documentstore1.dev.namespace.net/v2/service.svc";
}
public class Tests
{
[Theory]
[InlineData(Constants.Test1, 0)]
[InlineData(Constants.Test2, 1)]
public void ExampleTest(string url, int theoryIndex)
{
var test = url;
}
}
}

JPA Entities generation using JAX-WS on Netbeans with customized Methods

What I need is to have some specific methods (toString()) on my entities in order to be able to use them on my WebService Client (so I don't have to re-write them every time I Refresh my Webservice from Glassfish).
I ask this because I noticed that the only methods that are generated on my Client are the getters and setters of my fields, even if I write toString() on the Server side of the Webservice.
I guess the question is there a way to force customized methods to be deployed to the Application Server, so that those entities can reply to a toString(), for instance, on the Client?
package entities;
import java.io.Serializable;
import javax.persistence.*;
#Entity
public class Auxiliarfiles implements Serializable {
#Column(unique=false,updatable=true,insertable=true,nullable=false,length=38,scale=0,precision=0)
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private Long id;
#Column(unique=false,updatable=true,insertable=true,nullable=true,length=255,scale=0,precision=0)
#Basic
private String description;
#Column(unique=false,updatable=true,insertable=true,nullable=true,length=255,scale=0,precision=0)
#Basic
private String name;
public Auxiliarfiles(){}
public Long getId() {
return this.id;
}
public void setId (Long id) {
this.id = id;
}
public String getDescription() {
return this.description;
}
public void setDescription (String description) {
this.description = description;
}
public String getName() {
return this.name;
}
public void setName (String name) {
this.name = name;
}
public String toString() {
return this.getId() + " - " + this.getName();
}
}
Thanks in advance!

Can a particular constructor argument of an injected SUT using Autodata xUnit Theories?

Consider the following test,
[Theory, MyConventions]
public void GetClientExtensionReturnsCorrectValue(BuilderStrategy sut)
{
var expected = ""; // <--??? the value injected into BuilderStrategy
var actual = sut.GetClientExtension();
Assert.Equal(expected, actual);
}
and the custom attribute I'm using:
public class MyConventionsAttribute : AutoDataAttribute {
public MyConventionsAttribute()
: base(new Fixture().Customize(new AutoMoqCustomization())) {}
}
and the SUT:
class BuilderStrategy {
private readonly string _clientID;
private readonly IDependency _dependency;
public void BuilderStrategy(string clientID, IDependency dependency) {
_clientID = clientID;
_dependency = dependency;
}
public string GetClientExtension() {
return _clientID.Substring(_clientID.LastIndexOf("-") + 1);
}
}
I need to know what value was injected into the constructor parameter clientID so that I can use it to compare with the output of GetClientExtension. Is it possible to do this while still writing this style of test where the SUT is injected into the test method?
If you expose the injected clientID (and dependency as well) as read-only properties, you can always query their values:
public class BuilderStrategy {
private readonly string _clientID;
private readonly IDependency _dependency;
public void BuilderStrategy(string clientID, IDependency dependency) {
_clientID = clientID;
_dependency = dependency;
}
public string GetClientExtension() {
return _clientID.Substring(_clientID.LastIndexOf("-") + 1);
}
public string ClientID
{
get { return _clientID; }
}
public IDependency Dependency
{
get { return _dependency; }
}
}
This doesn't break encapsulation, but is rather known as Structural Inspection.
With this change, you could now rewrite the test like this:
[Theory, MyConventions]
public void GetClientExtensionReturnsCorrectValue(BuilderStrategy sut)
{
var expected = sut.ClientID.Substring(sut.ClientID.LastIndexOf("-") + 1);
var actual = sut.GetClientExtension();
Assert.Equal(expected, actual);
}
Some people don't like duplicating production code in the unit test, but I would rather argue that if you follow Test-Driven Development, it's the production code that duplicates the test code.
In any case, this is a technique known as Derived Value. In my opinion, as long as it retains a cyclomatic complexity of 1, we can still trust the test. Additionally, as long as the duplicated code only appears in two places, the rule of three suggests that we should keep it like that.

How to avoid casting between the DL - BL - UI layers ? (C#)

I designing an applications which basically has 3 different logic layers:
DB connector (implemented by ADO.NET).
BL the business logic (the only thing the UI knows).
DB repositories (connects between the first two).
The DB repositories are separated into sections of dependency and every final entity is polymorphic to one interface. In some cases there are dependencies between objects inside the same dependency sections - ISectionFactory (hence dependent).
In practice the BL is going to ask for an object of specific type (such as IngrediantType in my example) from the MainFactory (which is a factor for all the DB)
Because of this design I am forced to cast types on the UI - which obviously is a drag.
How can I change the design ?
Here is a brief look of design:
public class MainFactory
{
private Dictionary<Type, ISectionFactory> m_SectionsFactories;
private ISectionFactory treatmentsSectionFactory =
new TreatmentsSectionFactory();
public MainFactory()
{
m_SectionsFactories = new Dictionary<Type, ISectionFactory>
{
{typeof(IngrediantType),treatmentsSectionFactory}
};
}
public IConcreteDataCollection GetConcreteData(Type i_EntitiesName)
{
return m_SectionsFactories[i_EntitiesName]
.GetConcreteData(i_EntitiesName);
}
}
internal interface ISectionFactory
{
IConcreteDataCollection GetConcreteData(Type i_EntitiesName);
}
public class TreatmentsSectionFactory : ISectionFactory
{
private Dictionary<Type, IConcreteDataCollection>
m_ConcreteDataCollections;
private IngrediantTypes m_IngrediantTypes = new IngrediantTypes();
private Ingrediants m_Ingrediants = new Ingrediants();
public TreatmentsSectionFactory()
{
m_ConcreteDataCollections =
new Dictionary<Type, IConcreteDataCollection>();
m_ConcreteDataCollections
.Add(typeof(IngrediantType), m_IngrediantTypes);
m_ConcreteDataCollections
.Add(typeof(Ingrediants), m_Ingrediants);
}
public IConcreteDataCollection GetConcreteData(Type i_EntitiesName)
{
return m_ConcreteDataCollections[i_EntitiesName];
}
}
public interface IConcreteDataCollection : IEnumerable
{
// Iteratable.
IConcreteData GetById(int i_Id);
void AddNewConcreteData(IConcreteData i_ConcreteData);
void UppdateConcreteData(IConcreteData i_ConcreteData);
void DeleteConcreteData(IConcreteData i_ConcreteToDelete);
}
public class IngrediantTypes : IConcreteDataCollection
{
public string TestType { get; set; }
public IConcreteData GetById(int i_Id){}
public void AddNewConcreteData(IConcreteData i_ConcreteData){}
public void UppdateConcreteData(IConcreteData i_ConcreteData){}
public void DeleteConcreteData(IConcreteData i_ConcreteToDelete){}
public IEnumerator GetEnumerator(){}
}
// also implements IConcreteDataCollection
public class Ingrediants : IConcreteDataCollection
{
}
public interface IConcreteData
{
public int Index { set; get; }
} // the final (highest) entity of all DB entities
public class IngrediantType : IConcreteData
{
public int Index { set; get; }
// other set of properties
}
public class Ingrediant : IConcreteData
{
public int Index { set; get; }
public IngrediantType RelatedIngrediantType { set; get; }
// other set of properties
}
public class mainClass
{
public static void main()
{
MainFactory factory = new MainFactory();
var type = typeof(IngrediantType);
// returns a IngrdiantTypes of type (IConcreteDataCollection)
var t = factory.GetConcreteData(typeof(IngrediantType));
// I want to use the IngrediantType without casting !!!
var s = t.GetById(2);
}
}
It's a little hard to tell what's going on here, but I think the key will be to take advantage of generics like so:
public IConcreteDataCollection<T> GetConcreteData<T>()
{
return ...;
}
If I understand your question correctly, this will allow you to say:
var t = factory.GetConcreteData<IngrediantType>();
You will need to change almost every class in your code to use generics.

How to verify that method argument's property values are set when mocking methods with Moq?

Not sure if it has been asked before, here is the question.
Code first:
public class Customer {
public string Password { get; set; }
public string PasswordHash { get; set; }
}
public class CustomerService {
private ICustomerRepository _repo;
public CustomerService(ICustomerRepository repo) {
_repo = repo;
}
public int? AddCustomer(Customer customer) {
customer.PasswordHash = SHA1Hasher.ComputeHash(customer.Password);
return _repo.Add(customer);
}
}
public interface ICustomerRepository {
int? Add(Customer c);
}
public class CustomerRepository : ICustomerRepository {
int? AddCustomer(Customer customer) {
// call db and return identity
return 1;
}
}
[TestClass]
public class CustomerServiceTest {
[TestMethod]
public void Add_Should_Compute_Password_Hash_Before_Saving() {
var repoMock = new Mock<ICustomerRepository>();
//how do I make sure the password hash was calculated before passing the customer to repository???
}
}
How do I verify that CustomerService assigned the PasswordHash before passing the customer to repository?
There are several approaches you could take. Although not necessarily the best solution, here's one that doesn't require you to change your existing API. It assumes that SHA1Hasher.ComputeHash is a public method.
[TestClass]
public class CustomerServiceTest
{
[TestMethod]
public void Add_Should_Compute_Password_Hash_Before_Saving()
{
var customer = new Customer { Password = "Foo" };
var expectedHash = SHA1Hasher.ComputeHash(customer.Password);
var repoMock = new Mock<ICustomerRepository>();
repoMock
.Setup(r => r.Add(It.Is<Customer>(c => c.PasswordHash == expectedHash)))
.Returns(1)
.Verifiable();
// invoke service with customer and repoMock.Object here...
repoMock.Verify();
}
}
A slightly better solution would be to turn the SHA1Hasher into an injected service (such as IHasher) so that you can confirm that the PasswordHash property was assigned the value created by the IHasher instance.
Opening op your API even more, you could make the PasswordHash property virtual, so that you could pass a Mock Customer to the AddCustomer method to verify that the property was correctly set.
You could make SHA1Hasher non-static and virtual or wrap it in a ISHA1Hasher interface which can then be mocked. Wrapping static methods and objects in mockable classes is a classic way to increase testability.